# 视频稳定 if prev_frame is not None: # 计算帧间差分 diff = cv2.absdiff(frame, prev_frame) # 计算运动向量 _, motion = cv2.optflow.calcOpticalFlowFarneback(prev_frame, frame, None, 0.5, 3, 15, 3, 5, 1.2, 0) # 平移每一帧 M = np.float32([[1, 0, motion[:,:,0].mean()], [0, 1, motion[:,:,1].mean()]]) frame = cv2.warpAffine(frame, M, (frame.shape[1], frame.shape[0])) diff = cv2.warpAffine(diff, M, (diff.shape[1], diff.shape[0])) # 显示帧间差分 cv2.imshow('diff', diff) # 更新上一帧 prev_frame = frame.copy()将这段代码改为4.5.3版本opencv能用的代码
时间: 2023-11-21 18:05:56 浏览: 141
在 OpenCV 4.5.3 中,`calcOpticalFlowFarneback` 函数已经被移动到了 `cv2.optflow` 模块的子模块 `optflow_sparse` 中,并且函数名也发生了变化。下面是修改后的代码:
```python
# 初始化上一帧
prev_frame = None
while True:
# 读取视频帧
ret, frame = cap.read()
if not ret:
break
if prev_frame is not None:
# 计算帧间差分
diff = cv2.absdiff(frame, prev_frame)
# 计算运动向量
prev_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
flow = cv2.optflow.calcOpticalFlowSparseToDense(prev_gray, gray)
# 平移每一帧
M = np.float32([[1, 0, flow[:,:,0].mean()], [0, 1, flow[:,:,1].mean()]])
frame = cv2.warpAffine(frame, M, (frame.shape[1], frame.shape[0]))
diff = cv2.warpAffine(diff, M, (diff.shape[1], diff.shape[0]))
# 显示帧间差分
cv2.imshow('diff', diff)
# 更新上一帧
prev_frame = frame.copy()
# 显示视频帧
cv2.imshow('frame', frame)
# 按下 q 键退出循环
if cv2.waitKey(1) == ord('q'):
break
# 释放视频读取器和窗口
cap.release()
cv2.destroyAllWindows()
```
需要注意的是,我们需要先将当前帧和上一帧转换为灰度图像,然后再使用 `calcOpticalFlowSparseToDense` 函数计算运动向量。此外,由于光流法计算的运动向量可能存在噪点,因此在计算平移矩阵时,我们使用了运动向量的平均值。
阅读全文