How to do it...

You need to perform the following steps:

  1. Import the modules we're going to use:
import cv2import numpy as np
  1. Define the function to display the optical flow:
def display_flow(img, flow, stride=40):     for index in np.ndindex(flow[::stride, ::stride].shape[:2]):        pt1 = tuple(i*stride for i in index)        delta = flow[pt1].astype(np.int32)[::-1]        pt2 = tuple(pt1 + 10*delta)        if 2 <= cv2.norm(delta) <= 10:            cv2.arrowedLine(img, pt1[::-1], pt2[::-1], (0,0,255), 5, cv2.LINE_AA, 0, 0.4)            norm_opt_flow = np.linalg.norm(flow, axis=2)    norm_opt_flow = cv2.normalize(norm_opt_flow, None, 0, 1, cv2.NORM_MINMAX)        cv2.imshow('optical flow', img)    cv2.imshow('optical flow magnitude', norm_opt_flow)    k = cv2.waitKey(1)        if k == 27:        return 1    else:

Get OpenCV 3 Computer Vision with Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.