在開源視頻網(wǎng)站隨便找一個測試視頻,計算光流, 由于flow是二維的向量,可以通過mean操作得出當(dāng)前光流的方向。還可以使用FFMPEG倒放一下視頻,看看計算的光流方向是否相反ffmpeg -i Car.mp4 -vf reverse -af areverse car.mp4
。
# python 背景建模 opencv createBackgroundSubtractorMOG2 https://blog.csdn.net/ResumeProject/article/details/126195061
# opencv光流(密集光流+稀疏光流) cv.calcOpticalFlowPyrLK & cv2.calcOpticalFlowFarneback python與c++實現(xiàn) https://blog.csdn.net/ResumeProject/article/details/128507520
# opencv c++ Mat CUDA的編譯與使用 https://blog.csdn.net/ResumeProject/article/details/128540197
# 略修改與注釋
import numpy as np
import cv2
cap = cv2.VideoCapture(cv2.samples.findFile("Car.mp4"))
cv2.namedWindow('original frame', 0)
cv2.resizeWindow('original frame', 600, 500)
cv2.namedWindow('optical vis', 0)
cv2.resizeWindow('optical vis', 600, 500)
ret, frame1 = cap.read()
prvs = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
hsv = np.zeros_like(frame1)
hsv[..., 1] = 255
while(1):
ret, frame2 = cap.read()
if not ret:
print('No frames grabbed!')
break
next = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(prvs, next, None, 0.5, 3, 15, 3, 5, 1.2, 0)# 計算光流(只需要前后幀和一些參數(shù)即可)
# 由于flow是二維的向量,可以通過mean操作得出,當(dāng)前光流的方向
print(np.mean(flow[:,:,1]))
mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])# 轉(zhuǎn)為極坐標(biāo)
# 用hsv矩陣 (480, 640, 3) 保存
hsv[..., 0] = ang*180/np.pi/2
hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)# 轉(zhuǎn)為彩色圖像
cv2.imshow("original frame", frame2)
cv2.imshow('optical vis', bgr)
k = cv2.waitKey(30) & 0xff
k = cv2.waitKey(30) & 0xff
prvs = next
cv2.destroyAllWindows()
倒放效果你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧