在 python 中同时流式传输 2 个摄像头并支持网络摄像头

streaming 2 cameras at the same time in python with ip camera support

我希望能够通过 python 捕获 2 个或更多摄像机以应用一些对象检测代码。我想使用笔记本电脑的默认摄像头,并在另一个框架中使用具有域地址的 IP 摄像头。我可以通过 USB 插入另一个摄像头和 2 个帧弹出,它工作正常。但是当我尝试更改代码以使用 IP 摄像头时,我收到此错误:

ValueError:要解压的值太多(预期为 2)

这是流式传输 2 个或更多摄像机的代码

import urllib.request
import time
import numpy as np
import cv2

video_capture_0 = cv2.VideoCapture(0)
video_capture_1 = cv2.VideoCapture(1)

while True:
    
    ret0, frame0 = video_capture_0.read()
    ret1, frame1 = video_capture_1.read()
    

    if (ret0):
        cv2.imshow('Cam 0', frame0)

    if (ret1):
        cv2.imshow('Cam 1', frame1)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video_capture_0.release()
video_capture_1.release()
cv2.destroyAllWindows()

这是流式传输 IP 摄像机的代码

import urllib.request
import cv2
import numpy as np
import time
URL = "http://10.28.193.74:8080/shot.jpg"
while True:
    img_arr = np.array(bytearray(urllib.request.urlopen(URL).read()),dtype=np.uint8)
    img = cv2.imdecode(img_arr,-1)
    cv2.imshow('IPWebcam',img)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break;

    
cv2.destroyAllWindows()

这是我合并代码的糟糕尝试

import urllib.request
import cv2
import numpy as np
import time
URL = "http://10.28.193.74:8080/shot.jpg"
video_capture_0 = cv2.VideoCapture(0)
while True:
    ret0, frame0 = video_capture_0.read()
    img_arr = np.array(bytearray(urllib.request.urlopen(URL).read()),dtype=np.uint8)
    ret1, img = cv2.imdecode(img_arr,-1)

    if (ret0):
        
        cv2.imshow('Cam 0', frame0)

    if (ret1):

        cv2.imshow('IPWebcam',img)


    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    
cv2.destroyAllWindows()

乍一看 cv2.imdecode 不是 return ret1 的值

video_capture.read() 将 return 两个值: 一个布尔值,表示是否成功读取了帧 和一个包含框架

的 numpy 矩阵

它只是 return 一个图像的 numpy 矩阵,因此你只能解包一个值,而不是 2

你可以把if(ret1):换成if(img is not None):,也许是为了检查网络摄像头的帧是否是垃圾