In [1]:
from PIL import Image
from numpy import *
from pylab import *
from scipy import ndimage
In [2]:
import cv2
In [3]:
cap = cv2.VideoCapture(-1)
In [4]:
ret, im = cap.read()
print ret
In [7]:
while True:
ret, im = cap.read()
if not ret:
break
cv2.imshow('video', im)
key = cv2.waitKey(10)
if key == 27:
break
cv2.destroyAllWindows()
In [78]:
# Parameters
lk_params = dict(winSize=(15, 15), maxLevel=2,
criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
subpix_params = dict(zeroZone=(-1, -1), winSize=(10, 10),
criteria=(cv2.TERM_CRITERIA_COUNT | cv2.TERM_CRITERIA_EPS, 20, 0.03))
feature_params = dict(maxCorners=500, qualityLevel=0.01, minDistance=10)
cycle = 20
draw_flow = True
# Initialize
nbr_fetures = 0
prev = []
features = []
tracks = []
count = 0
while True:
ret, im = cap.read()
if not ret:
print "Image Capture Error"
break
image = im.copy()
if prev!=[]:
# for the first frame or after reset, detect points
if features==[]:
features = cv2.goodFeaturesToTrack(prev, **feature_params)
cv2.cornerSubPix(prev, features, **subpix_params)
tracks = [[p] for p in features.reshape((-1, 2))]
nbr_fetures = len(features)
# find the features in the new frame
img_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
tmp = float32(features). reshape(-1, 1, 2)
fs, status, track_error = cv2.calcOpticalFlowPyrLK(prev, img_gray, tmp, None, **lk_params)
features = [p for (st, p) in zip(status, fs) if st]
fs = array(fs).reshape((-1, 2))
for i, f in enumerate(fs):
tracks[i].append(f)
ndx = [i for (i, st) in enumerate(status) if not st]
ndx.reverse()
for i in ndx:
tracks.pop(i)
prev = img_gray
for point in features:
cv2.circle(image, (int(point[0][0]), int(point[0][1])), 3, (0, 255, 0), -1)
if draw_flow:
for t in tracks:
cv2.line(image, tuple(t[-1]), tuple(t[-2]), (0, 0, 255))
else:
prev = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
cv2.imshow('video', image)
key = cv2.waitKey(10)
if key == 27:
break
count += 1
if (count>=cycle or len(features)<nbr_fetures/2 or key==ord(' ')):
count = 0
features = []
cv2.destroyAllWindows()
In [ ]: