光流法python代码
时间: 2023-11-12 13:57:43 浏览: 162
以下是一个简单的光流法的 Python 代码示例:
```python
import cv2
cap = cv2.VideoCapture(0)
# 获取第一帧
ret, frame1 = cap.read()
# 转换为灰度图像
prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
# 创建 HSV 图像以便绘制光流
hsv = np.zeros_like(frame1)
hsv[...,1] = 255
while(1):
ret, frame2 = cap.read()
next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)
# 计算光流
flow = cv2.calcOpticalFlowFarneback(prvs,next,None,0.5,3,15,3,5,1.2,0)
# 绘制光流
mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])
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)
cv2.imshow('frame2',bgr)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
# 更新前一帧
prvs = next
cap.release()
cv2.destroyAllWindows()
```
阅读全文