如何在 OpenCV 中经过一定时间后自动关闭相机流?
How to automatically turn off a camera stream after a set amount of time in OpenCV?
我正在尝试编写一个程序,该程序将使用 OpenCV 检测运动并在超过 5 秒没有运动时关闭相机。该代码确实会打印“运动”并在关闭相机之前捕获大约 8-10 秒的运动,无论是否有运动。我不太确定代码的哪一部分导致了这个问题,我们将不胜感激!!
import cv2
import time
cap=cv2.VideoCapture(0)
ret1,background= cap.read()
gray1 = cv2.cvtColor(background, cv2.COLOR_BGR2GRAY)
gray1 = cv2.GaussianBlur(gray1, (21, 21), 0)
cv2.imshow('window',background)
t0 = time.time() # start time in seconds
imgCounter = 0
def getMovement (img):
motion = None
gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
gray2 = cv2.GaussianBlur(gray2, (21, 21), 0)
frameComparison=cv2.absdiff(gray1,gray2)
threshold = cv2.threshold(frameComparison, 25, 255, cv2.THRESH_BINARY)[1]
threshold = cv2.dilate(threshold,None)
countour,heirarchy = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i in countour:
if cv2.contourArea(i) < 50:
motion = False
continue
motion = True
return motion
while(True):
ret2,frame2=cap.read()
motion = getMovement(frame2)
cv2.imshow('window',frame2)
cv2.waitKey(1)
if motion:
print("MOTION")
else: # no motion for a bit, so the timer starts
t1 = time.time() # current time
num_seconds = t1 - t0 # diff
if num_seconds > 5:
# once it hits 5s, it should take a picture and turn off
print("No motion in 5s")
cv2.imwrite("Motion test.png", frame2)
break
cap.release()
cv2.destroyAllWindows()
我认为有一个小错误,即检测到运动时您不是 t0
。因此,您正在检查当前时间与计时器在开始时启动的时间之间的差异,同时检查是否没有运动。
所以在循环中试试这个:
if motion:
t0 = time.time()
print("MOTION")
我正在尝试编写一个程序,该程序将使用 OpenCV 检测运动并在超过 5 秒没有运动时关闭相机。该代码确实会打印“运动”并在关闭相机之前捕获大约 8-10 秒的运动,无论是否有运动。我不太确定代码的哪一部分导致了这个问题,我们将不胜感激!!
import cv2
import time
cap=cv2.VideoCapture(0)
ret1,background= cap.read()
gray1 = cv2.cvtColor(background, cv2.COLOR_BGR2GRAY)
gray1 = cv2.GaussianBlur(gray1, (21, 21), 0)
cv2.imshow('window',background)
t0 = time.time() # start time in seconds
imgCounter = 0
def getMovement (img):
motion = None
gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
gray2 = cv2.GaussianBlur(gray2, (21, 21), 0)
frameComparison=cv2.absdiff(gray1,gray2)
threshold = cv2.threshold(frameComparison, 25, 255, cv2.THRESH_BINARY)[1]
threshold = cv2.dilate(threshold,None)
countour,heirarchy = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i in countour:
if cv2.contourArea(i) < 50:
motion = False
continue
motion = True
return motion
while(True):
ret2,frame2=cap.read()
motion = getMovement(frame2)
cv2.imshow('window',frame2)
cv2.waitKey(1)
if motion:
print("MOTION")
else: # no motion for a bit, so the timer starts
t1 = time.time() # current time
num_seconds = t1 - t0 # diff
if num_seconds > 5:
# once it hits 5s, it should take a picture and turn off
print("No motion in 5s")
cv2.imwrite("Motion test.png", frame2)
break
cap.release()
cv2.destroyAllWindows()
我认为有一个小错误,即检测到运动时您不是 t0
。因此,您正在检查当前时间与计时器在开始时启动的时间之间的差异,同时检查是否没有运动。
所以在循环中试试这个:
if motion:
t0 = time.time()
print("MOTION")