三帧差分法python代码
时间: 2023-07-09 22:31:12 浏览: 69
以下是使用OpenCV库实现三帧差分法的Python代码:
```python
import cv2
cap = cv2.VideoCapture('video.mp4')
# 用于保存前两帧的图像
prev_frame = None
curr_frame = None
while True:
ret, frame = cap.read()
if not ret:
break
# 将当前帧转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if prev_frame is not None and curr_frame is not None:
# 计算前后两帧的差
diff1 = cv2.absdiff(curr_frame, prev_frame)
diff2 = cv2.absdiff(gray, curr_frame)
# 对两帧差取阈值
threshold1 = cv2.threshold(diff1, 30, 255, cv2.THRESH_BINARY)[1]
threshold2 = cv2.threshold(diff2, 30, 255, cv2.THRESH_BINARY)[1]
# 将两帧差进行AND操作,得到运动物体的二值图像
motion = cv2.bitwise_and(threshold1, threshold2)
cv2.imshow('Motion', motion)
# 更新前两帧的图像
prev_frame = curr_frame
curr_frame = gray
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
需要注意的是,这里使用了视频文件 `'video.mp4'`,如果要使用摄像头进行实时检测,则需要将 `cap` 的初始化改为 `cap = cv2.VideoCapture(0)`。
阅读全文