溫馨提示×

怎么使用OpenCV進行光流分析

小億
85
2024-05-22 16:15:14
欄目: 編程語言

要使用OpenCV進行光流分析,可以按照以下步驟進行:

  1. 導(dǎo)入OpenCV庫:
import cv2
  1. 讀取視頻幀并將其轉(zhuǎn)換為灰度圖像:
cap = cv2.VideoCapture('input_video.mp4')

ret, frame1 = cap.read()
prev_gray = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
  1. 初始化光流法參數(shù):
lk_params = dict( winSize  = (15,15),
                  maxLevel = 2,
                  criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
  1. 在循環(huán)中計算光流:
while True:
    ret, frame2 = cap.read()
    if not ret:
        break

    gray = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)

    # 計算光流
    flow = cv2.calcOpticalFlowFarneback(prev_gray, gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)

    # 在圖像上繪制光流
    for y in range(0, frame1.shape[0], 10):
        for x in range(0, frame1.shape[1], 10):
            dx, dy = flow[y, x]
            cv2.arrowedLine(frame2, (x, y), (int(x+dx), int(y+dy)), (0, 0, 255), 1)

    cv2.imshow('Optical Flow', frame2)

    if cv2.waitKey(30) & 0xFF == ord('q'):
        break

    prev_gray = gray

cap.release()
cv2.destroyAllWindows()

這樣就可以使用OpenCV計算視頻中的光流并顯示結(jié)果。在這個例子中,我們使用Farneback算法計算光流,并使用箭頭在圖像上顯示光流的方向。

0