如何解决带有Python的运动检测器异常工作
我使用cv2尝试编写了一个可以用作运动检测器的程序。
这是代码的主要部分:
from datetime import datetime
import pandas
import cv2
first_frame = None
status_list = [None,None]
times = []
df = pandas.DataFrame(columns=["Start","End"])
video = cv2.VideoCapture(0) # DirectShow (via videoInput)
while True:
check,frame = video.read()
status = 0
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) # Conversion from RGB to gray scale
gray = cv2.GaussianBlur(gray,(21,21),0)
if first_frame is None:
first_frame = gray # first frame is 'frame' on a gray scale
continue
delta_frame = cv2.absdiff(first_frame,gray)
thresh_frame = cv2.threshold(delta_frame,30,255,cv2.THRESH_BINARY)[1]
thresh_frame = cv2.dilate(thresh_frame,None,iterations=2)
(_,cnts,_) = cv2.findContours(thresh_frame.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for contour in cnts:
if cv2.contourArea(
contour) < 9000: # looking for moving areas with a contour greater than 7500px
continue
status = 1
(x,y,w,h) = cv2.boundingRect(
contour) # drawing a rectangle around the moving object
cv2.rectangle(frame,(x,y),(x + w,y + h),(230,0),3)
status_list.append(status)
# status_list contains only two values . if these values are different a time stamp will be added to the dataframe
status_list = status_list[-2:]
# status is either 1 or 0 ; 1 - moving object in frame ; 0- moving object not in frame
if status_list[-1] == 1 and status_list[-2] == 0:
times.append(datetime.now())
if status_list[-1] == 0 and status_list[-2] == 1:
times.append(datetime.now())
cv2.imshow("Threshold",thresh_frame)
cv2.imshow("delta",delta_frame)
cv2.imshow("Capturing",frame)
执行此脚本时,我可以看到在整个屏幕上都绘制了一个矩形(当背景完全静止且不在框架内时)
希望我能在我的代码中找不到任何缺陷。
我在内部添加了一些文档,因此更容易理解我的处理方式。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。