在OpenCV中经过设置的时间后,如何自动关闭摄像机流?

问题描述

我正在尝试编写一个程序,该程序将使用OpenCV检测运动并在无运动时间超过5s时关闭相机。该代码的确会打印“ Motion”,并在关闭相机之前捕获运动约8-10s,无论是否运动。我不太确定代码的哪一部分导致了这种情况,对您的帮助将不胜感激!

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,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")

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...