"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

February 13, 2019

Day #211- OpenCV based Optical Flow Example


#Modified and updated opencv example based on my requirements
#https://docs.opencv.org/3.1.0/d7/d8b/tutorial_py_lucas_kanade.html
import numpy as np
import cv2
cap = cv2.VideoCapture(r'E:\Optical_Flow\Demo.mp4')
#params for shitomasi corner detection
feature_params = dict(maxCorners=100,qualityLevel=0.3,minDistance=7,blockSize=7)
#parameters for lucas kanade optical flow
lk_params = dict(winSize=(15,15),maxLevel=2,criteria=(cv2.TERM_CRITERIA_EPS|cv2.TERM_CRITERIA_COUNT,10,0.03))
#Create some random colors
color = np.random.randint(0,255,(100,3))
#Take first frame and find corners in it
ret, old_frame = cap.read()
image = cv2.resize(old_frame, (500, 400))
old_gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
p0 = cv2.goodFeaturesToTrack(old_gray,mask=None,**feature_params)
#create mask for drawing purpose
mask = np.zeros_like(image)
final_frame = np.zeros_like(image)
while(1):
flag, frame1 = cap.read()
if flag:
frame = cv2.resize(frame1, (500, 400))
frame_gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
#calculate optical flow
p1,st,err = cv2.calcOpticalFlowPyrLK(old_gray,frame_gray,p0,None,**lk_params)
#select good points
good_new = p1[st==1]
good_old = p0[st==1]
print(good_new)
print(good_old)
#draw the tracks
for i,(new,old) in enumerate(zip(good_new,good_old)):
a,b = new.ravel()
c,d = old.ravel()
mask = cv2.line(mask,(a,b),(c,d),color[i].tolist(),2)
frame = cv2.circle(frame,(a,b),5,color[i].tolist())
img = cv2.add(frame,mask)
cv2.imshow('Intermediate frame',img)
final_frame = img.copy()
k = cv2.waitKey(30) & 0xff
if k==27:
break
#now update previous frame and previous points
old_gray = frame_gray.copy()
p0 = good_new.reshape(-1,1,2)
else:
break
cv2.destroyAllWindows()
#Hough Transformation
#Line Count
gray = cv2.cvtColor(final_frame,cv2.COLOR_BGR2GRAY)
img_gaussian = cv2.GaussianBlur(gray,(3,3),0)
img_sobelx = cv2.Sobel(img_gaussian,cv2.CV_8U,1,0,ksize=5)
img_sobely = cv2.Sobel(img_gaussian,cv2.CV_8U,0,1,ksize=5)
#Compute lines using Hough Transformation
xlines = cv2.HoughLines(img_sobelx,1,np.pi/180,200)
ylines = cv2.HoughLines(img_sobely,1,np.pi/180,200)
if(ylines is not None):
if(xlines is not None):
print('sobel - HoughLines')
c = ylines.size/xlines.size
print(c)
print('X Line Counts')
print(xlines)
print('Y Line Counts')
print(ylines)
cv2.imshow("Final Frame",final_frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
cap.release()
Happy Mastering DL!!!

No comments: