import cv2
# 创建 VideoCapture 对象,用于捕获视频
cap = cv2.VideoCapture(0) # 如果使用外部摄像头,请更改索引为相应设备的索引
# 定义前一帧和当前帧
previous_frame = None
current_frame = None
# 循环读取并处理视频帧
while True:
# 读取一帧视频
ret, frame = cap.read()
# 如果成功读取帧
if ret:
# 将帧转为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 进行高斯模糊以减少噪声
gray = cv2.GaussianBlur(gray, (21, 21), 0)
# 如果是第一帧,则将其保存为前一帧,并继续下一帧
if previous_frame is None:
previous_frame = gray
continue
# 计算当前帧与前一帧的差异
frame_delta = cv2.absdiff(previous_frame, gray)
# 对差异图像进行阈值处理,获得运动区域
thresh = cv2.threshold(frame_delta, 100, 255, cv2.THRESH_BINARY)[1]
# 对运动区域做轮廓检测
contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 遍历检测到的轮廓
for contour in contours:
# 忽略面积过小的轮廓
if cv2.contourArea(contour) < 500:
continue
# 在原始帧上绘制运动区域矩形框
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 显示帧
cv2.imshow('Video', frame)
# 更新前一帧为当前帧
previous_frame = gray
# 检测到按下 'q' 键,则退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放 VideoCapture 对象和窗口
cap.release()
cv2.destroyAllWindows()