以下はFarnebackメソッドでフレームごとのオプティカルフローを計算するためのPythonコードスニペットです。以下に示すものは完全な作業コードではありませんが(Web上に十分な例があります)、フローの計算方法を示しています。
#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×Wサイズであると仮定すると、以下のアサーションが成立します。
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、以下Farneback法上のドキュメントを調べると、次の文は、
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の範囲の角度を与えます。