2016-07-06 12 views
2

私はOpenCV-Python 3.1を使用しています。ここからのサンプルコードに続いて: http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.htmlデフォルトカメラの代わりにhttpカメラストリームを使用すると、 videocaptureは、カメラが物理的に切断されたときに「偽」(またはそれに関しては何も)を返さないので、プログラムを完全に凍結/凍結します。誰もがこれを修正する方法を知っていますか?opencv "False"を返す代わりにカメラが切断されたときにビデオキャプチャがハング/フリーズする

import numpy as np 
import cv2 

cap = cv2.VideoCapture('http://url') 

ret = True 

while(ret): 
    # Capture frame-by-frame 
    ret, frame = cap.read() 
    print(ret) 
    # Our operations on the frame come here 
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 

    # Display the resulting frame 
    cv2.imshow('frame',gray) 
    if cv2.waitKey(1) & 0xFF == ord('q'): 
     break 

# When everything done, release the capture 
cap.release() 
cv2.destroyAllWindows() 

答えて

1

蓋が閉じている(つまり、カムが利用できない)ときに、私のMacBookのウェブカムで同じ問題が発生しています。ドキュメントをすばやく見てから、VideoCaptureコンストラクタにはtimeoutというパラメータがないようです。だから、解決策は、この呼び出しをPythonから強制的に中断させる必要があります。

さらに、Pythonのasyncio、次にthreadingの一般的な情報を読んだあと、インタープリタの外でビジー状態になっているメソッドを中断する方法については何の手がかりも思いつきませんでした。だから私はVideoCaptureの呼び出しごとにデーモンを作成し、それを自分たちで死ぬことにした。

import threading, queue 

class VideoCaptureDaemon(threading.Thread): 

    def __init__(self, video, result_queue): 
     super().__init__() 
     self.daemon = True 
     self.video = video 
     self.result_queue = result_queue 

    def run(self): 
     self.result_queue.put(cv2.VideoCapture(self.video)) 


def get_video_capture(video, timeout=5): 
    res_queue = queue.Queue() 
    VideoCaptureDaemon(video, res_queue).start() 
    try: 
     return res_queue.get(block=True, timeout=timeout) 
    except queue.Empty: 
     print('cv2.VideoCapture: could not grab input ({}). Timeout occurred after {:.2f}s'.format(video, timeout)) 

誰かが優れている場合は、私はすべての耳です。

関連する問題