OpenCv Python框架在网络摄像头的mjpeg流中为空

时间:2015-07-08 13:31:20

标签: python opencv python-3.x stream mjpeg

我正在创建一个在网格中显示4个mjpg摄像头的程序,我的问题是,有时会发生框架为空并且流冻结,我通过检查每个框架的大小捕获错误,并且如果它等于1我继续循环,我的问题是我仍然在控制循环中,似乎流流不能获得有效的帧,任何建议?

import socket
import numpy as np
import cv2

cap = cv2.VideoCapture("http://85.90.40.19/mjpg/video.mjpg")
cap2 = cv2.VideoCapture("http://85.90.40.19/mjpg/video.mjpg")
cap3 = cv2.VideoCapture("http://85.90.40.19/mjpg/video.mjpg")
cap4 = cv2.VideoCapture("http://85.90.40.19/mjpg/video.mjpg")



cv2.namedWindow('frame', cv2.WND_PROP_FULLSCREEN)

cv2.setWindowProperty('frame', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)

while True:

    try:
         ret, frame = cap.read()
         ret2, frame2 = cap2.read()
         ret3, frame3 = cap2.read()
         ret4, frame4 = cap2.read()
     except:
         print("try catch")
         continue



     size = np.size(frame)
     size2 = np.size(frame2)
     size3 = np.size(frame3)
     size4 = np.size(frame4)


     if (size or size2 or size3 or size4) == 1:
        print("frame 0")
        continue

     # print("Dimensione" + str(size))

     rframe = cv2.resize(frame, (640,480))
     rframe2 = cv2.resize(frame2, (640,480))
     rframe3 = cv2.resize(frame3, (640,480))
     rframe4 = cv2.resize(frame4, (640,480))

     print(ret,ret2,ret3,ret4)


     vert1 = np.vstack((rframe,rframe2))
     vert2 = np.vstack((rframe3,rframe4))

     both = np.hstack((vert1,vert2))
     print(both.shape)
     # both.resize((1024, 768,3))

     cv2.imshow('frame', both)
     if cv2.waitKey(1) == 27:
         break

cap.release()
cv2.destroyAllWindows()

谢谢,抱歉我的英语不好

1 个答案:

答案 0 :(得分:0)

我可以建议以下类型的方法:

try:
    ret, frame = cap.read()
except:
    ret, frame = (-1, blackframe)

try:
    ret2, frame2 = cap2.read()
except:
    ret2, frame2 = (-1, blackframe)

try:
    ret3, frame3 = cap3.read()
except:
    ret3, frame3 = (-1, blackframe)

try:
    ret4, frame4 = cap4.read()
except:
    ret4, frame4 = (-1, blackframe)

其中blackframe是您在捕获失败时可用的合适图像。这将允许继续显示其他帧。

目的是删除导致执行返回到顶部的continue语句,而不让任何其他代码执行。