import cv2 import numpy as np from playsound import playsound import time

前一帧图像

previous_frame = None

变化帧计数器

frame_count = 0

开始时间

start_time = time.time()

打开摄像头

video_capture = cv2.VideoCapture(0)

while True: # 读取当前帧 ret, frame = video_capture.read()

# 将当前帧转换为灰度图像
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, 30, 255, cv2.THRESH_BINARY)[1]
# 对二值图像进行膨胀操作
thresh = cv2.dilate(thresh, None, iterations=2)

# 寻找轮廓
contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 初始化变化标识符
motion_detected = False

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)

    # 设置变化标识符为True
    motion_detected = True

if motion_detected:
    frame_count += 1
    # 如果变化帧计数器达到一定阈值(例如10帧),则开始计时
    if frame_count >= 10:
        elapsed_time = time.time() - start_time
        # 如果变化持续一分钟
        if elapsed_time >= 60:
            # 播放报警声音
            playsound('alarm.wav')
            cv2.putText(frame, 'Alarm', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
            cv2.putText(frame, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
else:
    # 重置变化帧计数器和开始时间
    frame_count = 0
    start_time = time.time()

# 显示当前帧
cv2.imshow('Motion Detection', frame)

# 按'q'键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
    break

释放摄像头和关闭窗口

video_capture.release() cv2.destroyAllWindows()


原文地址: https://www.cveoy.top/t/topic/p3rN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录