Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV Python calcOpticalFlowFarneback

Tags:

python

opencv

Thanks a lot, if any people can help me. Im try, use a example of book "OReilly Programming Computer Vision with Python", at end of page 216.

    #!/usr/bin/env python

import cv2
def draw_flow(im,flow,step=16):
    h,w = im.shape[:2]
    y,x = mgrid[step/2:h:step,step/2:w:step].reshape(2,-1)
    fx,fy = flow[y,x].T

    # create line endpoints
    lines = vstack([x,y,x+fx,y+fy]).T.reshape(-1,2,2)
    lines = int32(lines)

    # create image and draw
    vis = cv2.cvtColor(im,cv2.COLOR_GRAY2BGR)
    for (x1,y1),(x2,y2) in lines:
        cv2.line(vis,(x1,y1),(x2,y2),(0,255,0),1)
        cv2.circle(vis,(x1,y1),1,(0,255,0), -1)
    return vis


cap = cv2.VideoCapture(0)

ret,im = cap.read()
prev_gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)

while True:
    # get grayscale image
    ret,im = cap.read()
    gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)

    # compute flow
    #flow = cv2.calcOpticalFlowFarneback(prev_gray,gray,None,0.5,3,15,3,5,1.2,0)
    flow = cv2.calcOpticalFlowFarneback(prev_gray,gray,float(0),float(0),3,15,3,5,float(1),0)
    prev_gray = gray

    # plot the flow vectors
    cv2.imshow('Optical flow',draw_flow(gray,flow))
    if cv2.waitKey(10) == 27:
        break

Im execute in terminal (LXUbuntu, lxterminal) and i get the follow error:

VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
Traceback (most recent call last):
  File "hw.py", line 35, in <module>
    flow = cv2.calcOpticalFlowFarneback(prev_gray,gray,None,0.5,3,15,3,5,1.2,0)
TypeError: a float is required

I understand that the problem is in the function calcOpticalFlowFarneback, because this need a number in float, hence, im try calcOpticalFlowFarneback(prev_gray,gray,None,float(0.5),3,15,3,5,float(1.2),0) but dont work.

Thanks a lot.

like image 691
user1872896 Avatar asked Dec 03 '12 14:12

user1872896


1 Answers

You need to change the code a little bit.

First of all, include Numpy library since methods like mgrid, int32, vstack are numpy functions.

So at top of the code, add :

from numpy import *

Second, coming to your question, fourth argument should be an int. You have supplied it as float. Make it 1 (or 3, as you like). And last argument is output itself. You don't need it. So remove it.

So my final statement look like below (and it works fine for me) :

flow = cv2.calcOpticalFlowFarneback(prev_gray,gray,0.5,1,3,15,3,5,1)

Try this, and let me know if any error comes.

like image 140
Abid Rahman K Avatar answered Oct 04 '22 07:10

Abid Rahman K