当rtsp连接中断时,OpenCV-Python VideoCapture.read()不返回False

时间:2016-03-28 18:01:17

标签: python opencv video video-capture rtsp

我使用OpenCV 3.1和Python 3.4.3通过rtsp传输视频流。一切正常,但如果相机在运行时突然断开连接(即拔掉相机),程序将挂在self.capture.read()并且永远不会返回False值(或任何值)来处理关闭连接。这是我对在OpenCV中处理VideoCapture突然断开的理解。有没有更好的办法?

    """Classes for video processing"""
import cv2
from PyQt5 import QtGui, QtCore

from settings import CAMERA_IP_ADDRESS, CAMERA_PORT, FRAME_RATE
from structures import MessageLevel


class VideoStream(QtCore.QObject):
    """Class for displaying and recording video data."""
    logEvent = QtCore.pyqtSignal(MessageLevel, str)
    video_frame = QtCore.pyqtSignal(QtGui.QPixmap)
    video_timer = QtCore.QTimer()

    def __init__(self, parent=None):
        super(VideoStream, self).__init__(parent)
        self.connected = False
        self.stream = False
        self.video_timer.timeout.connect(self.stream_loop)
        self.video_width = 1280
        self.video_height = 720
        self.frame_rate_milliseconds = int(round(1/FRAME_RATE * 1000))
        self.save_path = None
        self.address_ip = None
        self.capture = None
        self.video_file = None

        self.url = 'rtsp://ip_path_to_camera' 

    def setup(self):
        """Function to set defautls and update GUI, should only be called once during GUI setup"""
        # Initialize variables
        self.set_address_ip(CAMERA_IP_ADDRESS)

    def connect(self):
        """Connect to rtsp video stream"""
        if not self.connected:
            self.video_file = cv2.VideoWriter(self.save_path, cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'),
                                              FRAME_RATE, (self.video_width, self.video_height))
            self.capture = cv2.VideoCapture(self.url)
        if self.capture.isOpened():
            self.connected = True
            self.stream = True
            self.video_timer.start(self.frame_rate_milliseconds)
        else:
            print('Device failed to connect')

    def stop(self):
        self.pause()
        self.connected = False
        self.capture.release()
        self.video_file = None

    def pause(self):
        self.video_timer.stop()
        self.stream = False

    def stream_loop(self):
        if self.stream:
            ret, frame = self.capture.read()
            if ret:
                self.video_file.write(frame)
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                image = QtGui.QImage(frame, self.video_width, self.video_height, QtGui.QImage.Format_RGB888)
                self.video_frame.emit(QtGui.QPixmap.fromImage(image))
            else:
                print('Device diconnected')
                self.stop()

    def set_address_ip(self, ip_address):
        self.address_ip = ip_address
        self.address_ip_signal.emit(self.address_ip)

    def log_message(self, level, message):
        self.logEvent.emit(level, message)

0 个答案:

没有答案