【问题标题】:How to automatically turn off a camera stream after a set amount of time in OpenCV?如何在 OpenCV 中设定时间后自动关闭相机流?
【发布时间】:2020-12-06 19:35:57
【问题描述】:

我正在尝试编写一个程序,该程序将使用 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()

【问题讨论】:

    标签: opencv computer-vision video-processing


    【解决方案1】:

    我认为有一个小错误,即当检测到运动时您不是t0。因此,在检查没有运动时,您正在获取当前时间与开始时启动计时器的时间之间的差异。

    所以在循环中试试这个:

    if motion:
        t0 = time.time()
        print("MOTION")
    

    【讨论】:

    • 我刚刚尝试过,这正是我所需要的!我没想过重新启动计时器。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 2013-05-23
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多