如何从OpenCV中提取像素的速度向量calcOpticalFlowFarneback - Python版本)

时间:2017-04-11 16:53:12

标签: python opencv computer-vision opticalflow

我想提取两帧之间每个像素的光流速度矢量。我正在使用OpenCV函数如下:

flow = calcOpticalFlowFarneback(Previous_Gray, Current_Gray, Optical_Flow, 0.5, 3, 15, 3, 5, 1.2, 0);

Previous_Gray = previous frame 
Current_Gray = current frame 

我想知道flow的格式是什么以及如何提取它。

非常感谢您的帮助! : - )

P.S。我知道我的问题几乎与这个问题相同:How to extract velocity vectors of a pixels from calcOpticalFlowFarneback。但是,我正在使用Python进行编码,并希望在Python中使用解决方案。

1 个答案:

答案 0 :(得分:1)

下面给出了用于通过Farneback方法计算每帧光流的python代码片段。尽管下面给出的不是完整的工作代码(网上有足够的例子),但它显示了如何计算流量。

#use this params
farneback_params={
        'pyr_scale':0.5,
        'levels':3,
        'winsize':15,
        'iterations': 3,
        'poly_n': 5,
        'poly_sigma':1.2,
        'flags':cv2.OPTFLOW_USE_INITIAL_FLOW
    }

#do initializations
while True:
    #for every frame,
    #get current_frame_gray
    flow = cv2.calcOpticalFlowFarneback(prev_frame_gray, current_frame_gray, flow, **farneback_params)
    prev_frame_gray = current_frame_gray

如果假设每个帧都是H x W大小,则以下断言成立。

assert(flow.shape == (H, W, 2))
assert(flow.dtype == numpy.float32)

如果您查看以下Farneback方法的文档,
http://docs.opencv.org/3.0-beta/modules/video/doc/motion_analysis_and_object_tracking.html,以下声明为

for r in range(H):
    for c in range(W):
        prev_frame_gray[r,c] corresponds to current_frame_gray[r + flow[r,c, 1], c+ flow[r,c,0]]

所以前一帧(prev_frame_gray)的每个像素的速度分量是

flow[r,c,0] in x- direction (columns)
flow[r,c,1] in y- direction (rows)

正如各种代码示例所示,您可以通过以下简单命令以极坐标形式(幅度,角度)轻松表达流程

mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])

mag和ang的形状为(H,W),dtype为numpy.float32。 ang结果给出的角度范围为0-2pi。