Python 断开USB摄像头时,VideoCapture read()返回True

Python 断开USB摄像头时,VideoCapture read()返回True,python,opencv,camera,Python,Opencv,Camera,当我断开USB摄像头时,read()函数返回True,所以程序不会尝试重新连接自身,它会输出一个黑色图像 当我在USB卡马拉断开连接的情况下启动程序时,它会报告相同的情况 self.stream.isOpened()也返回True class VideoGet: def __init__(self, src=0): self.src = src self.stopped = False self.Q = [] self.sc

当我断开USB摄像头时,read()函数返回True,所以程序不会尝试重新连接自身,它会输出一个黑色图像

当我在USB卡马拉断开连接的情况下启动程序时,它会报告相同的情况

self.stream.isOpened()也返回True

class VideoGet:
    def __init__(self, src=0):
        self.src = src
        self.stopped = False
        self.Q = []
        self.scale_percent = 100
        self.grabbed = False
        self.frame = None
        self.stream = cv2.VideoCapture(self.src)
    def start(self):
        threading.Thread(target=self.get, args=()).start()
        return self
    def get(self):

        while True:
            self.stream = cv2.VideoCapture(self.src)
            (self.grabbed, preFrame) = self.stream.read()
            if self.grabbed is True:
                print('Iniciando camara')
                while True:
                    try:
                        (self.grabbed, preFrame) = self.stream.read()
                        self.width = int(preFrame.shape[1] * self.scale_percent / 100)
                        self.height = int(preFrame.shape[0] * self.scale_percent / 100)
                        dim = (self.width, self.height)
                        self.frame = cv2.resize(preFrame, dim, interpolation=cv2.INTER_AREA)
                        if len(self.Q) >= cfg['config']['tiempoPre']:
                            self.Q.pop(0)
                            self.Q.append(self.frame)
                        else:
                            self.Q.append(self.frame)
                    except Exception as e:
                        self.grabbed = False
                        self.stream.release()
                        del(self.stream)
                        break

    def stop(self):
        self.stopped = True
编辑:当重新连接到IP摄像头时,它工作正常


Edit2:通过读取图像并进行np.sum运算,然后检查该值是否大于阈值,解决了该问题。

断开连接时会发生什么情况?你的程序会得到什么样的图像?您可以随时检查图像是否为空。也许在您的情况下,“获取结果为真+图像为空”意味着相机已断开连接?如果图像不是空的,可能驱动程序的缓冲区中仍有图像?这可能意味着你的程序捕获速度太慢。当我断开连接时,我会得到图像,但它们是黑色的,所以正如你说的,我正在检查图像是否为“空的”(不是完全黑色),设置一个np.sum低于某个值的值。可能是驱动程序实现中的一个错误概念。。。