2017-01-15 35 views
1

我在python中使用cv2.calcOpticalFlowFarneback()來獲得光流的結果,但在嘗試使用它的結果時出現問題。我想繪製該函數返回的更改,但在Python中循環太慢。我相信有一種方法可以讓它更快。這是我嘗試OpenCV中沒有循環的calcOpticalFlowFarneback的繪製結果

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

您可以使用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