다음은 Farneback 메서드로 모든 프레임의 옵티컬 플로우를 계산하기위한 파이썬 코드 조각입니다. 아래에 주어진 것은 완전한 작업 코드는 아니지만 (웹 주위에 이것에 대한 예제가 충분히 있습니다), 흐름 계산 방법을 보여줍니다.
#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 크기라고 가정하면 다음 어설 션이 적용됩니다. 아래 Farneback 방법에 대한 문서를 살펴보면
assert(flow.shape == (H, W, 2))
assert(flow.dtype == numpy.float32)
,
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])
탄창과 중앙 형상의 것 (H, W) 및 DTYPE numpy.float32 의해, 각도). ang 결과는 0-2pi 범위의 각도를 제공합니다.