用opencv python 写代码要求如下:检测到区域入侵超过半分钟就显示超时并发出声音报警区域由我划定 在画面上显示时间和入侵位置。
下面是使用OpenCV和Python编写的代码,实现了检测到区域入侵超过半分钟后显示超时并发出声音报警,并在画面上显示时间和入侵位置。
import cv2
import numpy as np
import time
import winsound
# 设置视频路径或摄像头索引
video_path = 'path_to_video_file.mp4' # 或者使用摄像头:0
# 设置区域坐标(矩形左上角和右下角坐标)
region_of_interest = [(100, 100), (300, 300)]
# 初始化入侵时间和报警状态
invasion_start_time = None
alarm_triggered = False
# 加载视频
cap = cv2.VideoCapture(video_path)
# 创建窗口
cv2.namedWindow('Invasion Detection')
while True:
# 读取视频帧
ret, frame = cap.read()
if not ret:
break
# 从帧中提取区域
roi = frame[region_of_interest[0][1]:region_of_interest[1][1], region_of_interest[0][0]:region_of_interest[1][0]]
# 将区域转换为灰度图像
gray_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
# 对灰度图像进行高斯模糊
blurred_roi = cv2.GaussianBlur(gray_roi, (5, 5), 0)
# 进行边缘检测
edges = cv2.Canny(blurred_roi, 50, 150)
# 执行霍夫线变换
lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=100, minLineLength=100, maxLineGap=10)
if lines is not None:
# 检测到入侵
if invasion_start_time is None:
invasion_start_time = time.time()
print("Invasion started at:", time.ctime())
# 绘制检测到的线段
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(roi, (x1, y1), (x2, y2), (0, 0, 255), 2)
else:
# 未检测到入侵
if invasion_start_time is not None:
# 判断入侵时间是否超过半分钟
if time.time() - invasion_start_time > 30:
print("Invasion timeout!")
alarm_triggered = True
winsound.Beep(1000, 2000) # 播放声音报警
invasion_start_time = None
# 在画面上显示时间
cv2.putText(frame, time.ctime(), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
# 在画面上显示入侵位置
cv2.rectangle(frame, region_of_interest[0], region_of_interest[1], (0, 255, 0), 2)
# 在画面上显示结果
cv2.imshow('Invasion Detection', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
在使用代码前,请确保已经安装了OpenCV和winsound库。可以通过以下命令安装:
pip install opencv-python
pip install opencv-python-headless
pip install pywin32
请注意,代码中的video_path变量是视频文件的路径,或者可以使用摄像头的索引(例如0表示第一个摄像头)。region_of_interest变量定义了感兴趣的区域,根据需要进行调整
原文地址: http://www.cveoy.top/t/topic/h0qb 著作权归作者所有。请勿转载和采集!