Guest User

Optical flow for a video

a guest
Dec 30th, 2016
474
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. import numpy as np
  2. import cv2
  3.  
  4. def getFeaturesToDetect():
  5.     return
  6.  
  7. cap = cv2.VideoCapture('/home/rish/Code/Datasets/video-walking/person25_walking_d3_uncomp.avi')
  8. #cap = cv2.VideoCapture(0)
  9. cap.set(cv2.CAP_PROP_FRAME_WIDTH, 500)
  10. cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 500)
  11.  
  12. if not cap.isOpened():
  13.     CV_ASSERT("Cam open failed")
  14.  
  15. feature_params = dict ( maxCorners = 10,
  16.                         qualityLevel = 0.3,
  17.                         minDistance = 7,
  18.                         blockSize = 7)
  19. lk_params = dict (  winSize = (15,15),
  20.                     maxLevel = 2,
  21.                     criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
  22.  
  23. color = np.random.randint(0,255, (100,3))
  24.  
  25. ret, old_frame = cap.read()
  26. old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
  27. p0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params)
  28. totalFeatures = len(p0)
  29. mask = np.zeros_like(old_frame)
  30.  
  31. while(1):
  32.     ret, frame = cap.read()
  33.     frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  34.    
  35.     p1,st,err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)
  36.  
  37.     good_new = p1[st==1]
  38.     good_old = p0[st==1]
  39.  
  40.     # draw the tracks
  41.     for i,(new,old) in enumerate(zip(good_new,good_old)):
  42.         a,b = new.ravel()
  43.         c,d = old.ravel()
  44.         mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
  45.         frame = cv2.circle(frame,(a,b),5,color[i].tolist(),-1)
  46.     img = cv2.add(frame,mask)
  47.    
  48.     cv2.imshow("optical flow", img)
  49.     k = cv2.waitKey(100) & 0xff
  50.     if k == 27:
  51.         break
  52.  
  53.     # update features
  54.     if len(p1) <= totalFeatures / 2:
  55.         old_gray = frame_gray.copy()
  56.         p0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params)
  57.         totalFeatures = len(p0)
  58.         mask = np.zeros_like(old_frame) # keep this line if you would like to remove all previously drawn flows
  59.     else :
  60.         old_gray = frame_gray.copy()
  61.         p0 = good_new.reshape(-1,1,2)
  62.  
  63. cv2.destroyAllWindows()
  64. cap.release()
Add Comment
Please, Sign In to add comment