import cv2
import numpy as np
def opticalflow():
video=cv2.VideoCapture('traffic.mp4')
fourcc=cv2.VideoWriter_fourcc(*'XVID')
out=cv2.VideoWriter('output.avi',fourcc,30.0,(640,360))
#creating a dict for shi-tomasi corener detection by specifying the parameters
stomasi_features=dict(
maxCorners = 100,
qualityLevel = 0.01,
minDistance = 10,
blockSize = 7 )
#creater a dict to pre specify parameters for lucas kanade method
lk_parameters=dict(
winSize = (15,15),
maxLevel = 2,
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03)
)
#creating random colors
colors=np.random.randint(0,255,(100,3))
#now we take first frame and detec shi-tomasi corners in it by first reading the #frame and then converting it to gray scale and then using cv2.goodfeatures totrack() #method
ret,frame1=video.read()
frame1_gray=cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
F1_points=cv2.goodFeaturesToTrack(frame1_gray,mask=None,**stomasi_features)
#create maask img for drawing
mask=np.zeros_like(frame1)
#now here we read the next frame convert it to grayscale then calculate optical flow #in the new frame and the frame 1
while True:
ret,frame2=video.read()
frame2_gray=cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)
F2_points,status,err=cv2.calcOpticalFlowPyrLK(frame1_gray,frame2_gray,F1_points,None,**lk_parameters)
#selecting good points from the above optical flow method and comparing it with old #points
good_new=F2_points[status==1]
good_old=F1_points[status==1]
#drawing lines
for colour,(new,old) in enumerate(zip(good_new,good_old)):
a,b=new.ravel() #this the coordinate of the new point from the frame 2
c,d=old.ravel() #this is coordinateof old point from frame 1
mask= cv2.line(mask,(int(a),int(b)),(int(c),int(d)),colors[colour].tolist(),2)
frame2=cv2.circle(frame2,(int(a),int(b)),5,colors[colour].tolist(),-1)
img=cv2.add(frame2,mask)
#out.write(img)
cv2.imshow('FRAME',img)
cv2.imshow('mask',mask)
out.write(img)
k = cv2.waitKey(30)
if k == 27 & 0xff:
break
#update previous points and frame
frame1_gray=frame2_gray.copy()
F1_points=good_new.reshape(-1,1,2)
cv2.destroyAllWindows()
out.release()
video.release()
if __name__ == '__main__':
opticalflow()