Complete the code to calculate the optical flow using Lucas-Kanade method.
flow = cv2.calcOpticalFlow[1](prev_gray, next_gray, None, lk_params['winSize'], lk_params['maxLevel'], lk_params['criteria'])
The Lucas-Kanade method is called using cv2.calcOpticalFlowPyrLK in OpenCV.
Complete the code to convert a video frame to grayscale for optical flow calculation.
gray_frame = cv2.cvtColor(frame, [1])Optical flow algorithms require grayscale images, so we convert BGR frames to grayscale using cv2.COLOR_BGR2GRAY.
Fix the error in the code to calculate the magnitude and angle of optical flow vectors.
magnitude, angle = cv2.cartToPolar(flow[..., 0], flow[..., [1]], angleInDegrees=True)
The optical flow has two channels: horizontal (index 0) and vertical (index 1). We use index 1 for the vertical component.
Fill both blanks to create a mask image that visualizes optical flow direction and magnitude.
mask = np.zeros_like(frame) mask[..., [1]] = angle / 2 mask[..., [2]] = 255
Hue channel is at index 0 and saturation channel is at index 1 in HSV images.
Fill all three blanks to convert the mask to BGR color and display it with OpenCV.
rgb_flow = cv2.cvtColor(mask, [1]) cv2.imshow('Optical Flow', rgb_flow) cv2.waitKey([2]) cv2.destroyAllWindows() # Wait time of [3] milliseconds allows frame update
We convert HSV mask to BGR for display using cv2.COLOR_HSV2BGR. A waitKey of 0 waits indefinitely, but 30 ms allows smooth video playback.