在没有循环的OpenCV中绘制calcOpticalFlowFarneback的结果

时间:2017-01-15 13:19:06

标签: python opencv numpy image-processing opticalflow

我在python中使用cv2.calcOpticalFlowFarneback()来获取光流的结果,但在尝试使用它的结果时出现了问题。我想绘制该函数返回的更改但是在python中循环太慢了。我确信有一种方法可以使numpy更快。这是我的尝试

flow = cv2.calcOpticalFlowFarneback(prev_gray, gray, pyr_scale=0.5, levels=5, winsize=13, iterations=10, poly_n=5, poly_sigma=1.1, flags=0,flow=None) 

for y in range(0, flow.shape[0], 5):

    for x in range(0, flow.shape[1], 5):

        fx, fy = flow[y, x]

        cv2.line(frame2, (x,y), (int(x+fx),int(y+fy)), (255,0,0))
        cv2.circle(frame2, (x,y), 1, (255,0,0), -1)

1 个答案:

答案 0 :(得分:1)

您可以使用openCV方法cv2.polylines()绘制多边形曲线数组,而不必使用for循环进行迭代。

这是一个代码示例

   def draw_flow(self, img, flow, step=16):
    h, w = img.shape[:2]
    y, x = np.mgrid[step / 2:h:step, step / 2:w:step].reshape(2, -1).astype(int)
    fx, fy = flow[y, x].T
    lines = np.vstack([x, y, x + fx, y + fy]).T.reshape(-1, 2, 2)
    lines = np.int32(lines + 0.5)
    vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    cv2.polylines(vis, lines, 0, (0, 255, 0))
    for (x1, y1), (x2, y2) in lines:
        cv2.circle(vis, (x1, y1), 1, (0, 255, 0), -1)
    return vis

查看openCV示例以下载并运行完整代码https://github.com/opencv/opencv/blob/master/samples/python/opt_flow.py

或openCV文档,以获取有关折线http://docs.opencv.org/3.0-beta/modules/imgproc/doc/drawing_functions.html#polylines

的更多信息