如何限制相机在 python、opencv 上拍摄和不拍摄图像?

How to restrict a camera on capturing and not capturing images on python, opencv?

我有一个面向 LED 传感器的摄像头,我想在物体在视线范围内时限制捕捉图像,否则无法捕捉。我将指定一个点或区域,当对象到达时颜色像素将发生变化,它将等待 3 秒然后捕获。此后,如果它仍然留在指定区域,则不会捕获同一对象。这是我的代码。

import cv2
import numpy as np
import os
os.chdir('C:/Users/Man/Desktop')
previous_flag = 0
current_flag = 0
a = 0
video = cv2.VideoCapture(0)
while True:
    ret, frame = video.read()
    rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    cv2.imshow('Real Time', rgb)
    cv2.waitKey(1)
    if(rgb[400, 200, 0]>200): # selecting a point that will change in terms of pixel values
        current_flag = 0
        previous_flag = current_flag
        print('No object Detected')
    else: # object arrived
        current_flag = 1
        change_in_flags = current_flag - previous_flag
        if(change_in_flags==1):
            time.sleep(3)
            cv2.imwrite('.trial/cam+str(a).jpg', rgb)
            a += 1
            previous_flag = current_flag
video.release()
cv2.destroyAllWindows()

当我执行上面的程序时,对于第一种情况(如果),它会打印几行 No object Detected.

如何减少 No object Detected 语句的顺序打印行?这样程序就可以只打印一行而不会重复。 我还尝试添加一个 while 循环以在 a+=1 之后保持当前状态为真,例如:

while True:
    previous_flag = current_flag
    continue

它成功了,但是系统变得很慢,有什么办法可以避免这样的 while 循环,从而使系统变得更快?有什么建议

import cv2
import numpy as np
import os
os.chdir('C:/Users/Man/Desktop')
state1=0
a = 0
video = cv2.VideoCapture(0)
while True:
    ret, frame = video.read()
    rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    cv2.imshow('Real Time', rgb)
    cv2.waitKey(1)
    if(rgb[400, 200, 0]>200): # selecting a point that will change in terms of pixel values
        if(state1 == 0):
            print('No object Detected')
        state1=1
    else: # object arrived
        time.sleep(1)
        if(state1==1)
           print('Object is detected')
           cv2.imwrite('./trial/cam+str(a).jpg', rgb)
           a += 1
        state1=0
video.release()
cv2.destroyAllWindows()