使用cv2对rtsp协议的摄像头捕捉视频流偶尔触发'cv::imencode'异常

最近学习cv2通过flask直播rtsp摄像头视频流,发现在实际的运行中,偶尔出触发错误(大部分是正常的):

cv2.error: OpenCV(4.3.0) C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp: 919 : error: (-215:Assertion failed) !image.empty() in function ‘cv::imencode’
Debugging middleware caught exception in streamed response at a point where response headers were already sent.
Traceback (most recent call last):

从错误来看,可能是cv::imencode 编码图片的时候抛出的异常,但是百思不得其解。定位错误代码位置在:

ret, jpeg = cv2.imencode(‘.jpg’, image)

下面是我的代码,不知道有没有朋友遇到同样问题,可否指点一二。

以下代码包含在一个videoCamera类中

import cv2


# 获取摄像头视频流,将图像流转换为图帧
class VideoCamera(object):
    def __init__(self, rtsp_url):
        self.cap = cv2.VideoCapture(rtsp_url)

    def __del__(self):
        self.cap.release()

    def get_frame(self):
        success, image = self.cap.read()
        ret, jpeg = cv2.imencode('.jpg', image)  # 从网络读取图像数据并压缩编码转换成图片格式
        return jpeg.tobytes()

# debug test
VideoCamera("rtsp://admin:12345@192.168.1.122/h264/ch1/main/av_stream")
Jason990420
最佳答案

會不會是因为没有对 read 结果作任何检查, image 為 None

If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer.

>>> cv2.imencode('.jpg', None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
cv2.error: OpenCV(4.3.0) C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:919: error: (-215:Assertion failed) !image.empty() in function 'cv::imencode'
3年前 评论
讨论数量: 2
Jason990420

會不會是因为没有对 read 结果作任何检查, image 為 None

If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer.

>>> cv2.imencode('.jpg', None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
cv2.error: OpenCV(4.3.0) C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:919: error: (-215:Assertion failed) !image.empty() in function 'cv::imencode'
3年前 评论

@Jason990420 你这样一说,应该是这个问题,我顺着思路改善一下。

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!