You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Django中使用OpenCV实现RTSP监控流时遇OpenCV错误求助

解决Django推送RTSP流时的OpenCV断言错误

错误原因分析

你遇到的cv2.error: (-215:Assertion failed) size.width>0 && size.height>0错误,本质是cv2.read()读取到了空帧(frame为None),核心问题有两个:

  1. 类结构错误:videoCamera类的顶层直接写了while循环和imshow,这会在类定义时就执行,而非实例化后调用;且Django服务器运行在无GUI环境,imshow完全无效。
  2. RTSP流连接失败:你的RTSP地址格式可能有误,或者摄像头未正确授权,导致cv2.VideoCapture无法正常获取流。

修复步骤与完整代码

1. 重构videoCamera类

将视频初始化和帧读取逻辑封装到类方法中,移除图形界面相关代码。

2. 实现帧生成器gen

Django的StreamingHttpResponse需要生成器逐帧输出图像数据,需将OpenCV帧转换为JPEG字节流。

3. 修正RTSP地址格式

确保地址符合标准格式:rtsp://[用户名]:[密码]@[IP地址]:[端口]/[流路径]

完整修复代码

from django.shortcuts import render
from django.views.decorators import gzip
from django.http import StreamingHttpResponse
import cv2
import numpy as np

# 帧生成器:逐帧输出JPEG格式的图像字节流
def gen(camera):
    while True:
        frame = camera.get_frame()
        if frame is None:
            continue
        # 将OpenCV帧转换为JPEG字节流
        _, jpeg = cv2.imencode('.jpg', frame)
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + jpeg.tobytes() + b'\r\n\r\n')

@gzip.gzip_page
def Home(request):
    try:
        cam = videoCamera()
        if not cam.is_opened:
            raise Exception("无法连接RTSP流")
        return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame")
    except Exception as e:
        print(f"错误信息: {str(e)}")
        return render(request, 'index.html')

class videoCamera(object):
    def __init__(self):
        # 替换为你的真实RTSP地址
        self.video = cv2.VideoCapture("rtsp://[用户名]:[密码]@[IP地址]:554/sub")
        self.is_opened = self.video.isOpened()

    def get_frame(self):
        if not self.is_opened:
            return None
        ret, frame = self.video.read()
        if ret:
            return frame
        else:
            # 读取失败时尝试重新连接
            self.video.release()
            self.video = cv2.VideoCapture("rtsp://[用户名]:[密码]@[IP地址]:554/sub")
            self.is_opened = self.video.isOpened()
            return None

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

额外排查步骤

  • 单独验证RTSP连接:用以下脚本确认地址有效性:
    import cv2
    cap = cv2.VideoCapture("你的真实RTSP地址")
    if cap.isOpened():
        ret, frame = cap.read()
        print("RTSP流连接正常,读取帧成功" if ret else "连接成功但无法读取帧")
        cap.release()
    else:
        print("无法连接RTSP流,请检查地址、权限或摄像头状态")
    
  • 检查摄像头设置:确保摄像头允许外部IP访问RTSP流,且用户名密码正确。
  • 确认依赖安装:服务器需安装opencv-python和numpy,执行pip install opencv-python numpy完成安装。

内容的提问来源于stack exchange,提问作者Diaruys

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 17:50:24