Skip to content

Instantly share code, notes, and snippets.

@yudai09
Created March 20, 2021 06:30
Show Gist options
  • Save yudai09/335716ab86dc2a8a1c4ac0c51f9a9307 to your computer and use it in GitHub Desktop.
Save yudai09/335716ab86dc2a8a1c4ac0c51f9a9307 to your computer and use it in GitHub Desktop.
import numpy as np
import cv2 as cv
# Most of the code come from https://docs.opencv.org/master/d4/dee/tutorial_optical_flow.html
# But, The algorithm is changed to TVL-1
cap = cv.VideoCapture(cv.samples.findFile("vtest.avi"))
ret, frame1 = cap.read()
prvs = cv.cvtColor(frame1, cv.COLOR_BGR2GRAY)
hsv = np.zeros_like(frame1)
hsv[..., 1] = 255
while(1):
ret, frame2 = cap.read()
next = cv.cvtColor(frame2, cv.COLOR_BGR2GRAY)
# TVL-1
# opencv_python==4.1.2.30
# opencv-contrib-python==4.1.2.30
optical_flow = cv.optflow.DualTVL1OpticalFlow_create()
flow = optical_flow.calc(prvs, next, None)
mag, ang = cv.cartToPolar(flow[..., 0], flow[..., 1])
hsv[..., 0] = ang*180/np.pi/2
hsv[..., 2] = cv.normalize(mag, None, 0, 255, cv.NORM_MINMAX)
bgr = cv.cvtColor(hsv, cv.COLOR_HSV2BGR)
cv.imshow('frame2', bgr)
k = cv.waitKey(30) & 0xff
if k == 27:
break
elif k == ord('s'):
cv.imwrite('opticalfb.png', frame2)
cv.imwrite('opticalhsv.png', bgr)
prvs = next
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment