#! /usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import cv2 width = 320 height = 240 margin = 50 cap = cv2.VideoCapture(0) # Let us resize the video to width x height cap.set(3,width) cap.set(4,height) # We need global variables previous_frame = None hsv = np.zeros((height, width, 3), dtype = np.uint8) hsv[...,1] = 255 # Processing starts while(True): is_ok, frame = cap.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if previous_frame != None : flow = cv2.calcOpticalFlowFarneback(previous_frame, frame, 0.5, 3, 10, 3, 5, 1.2, 0) mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1]) hsv[...,0] = ang*180/np.pi/2 hsv[...,2] = cv2.normalize(mag,None,0,255,cv2.NORM_MINMAX) cv2.imshow('display',cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR)) if cv2.waitKey(1) & 0xFF == 27: #27 is the ascii for escape break previous_frame = frame # When everything done, release the capture cap.release() cv2.destroyAllWindows()