首页 > 解决方案 > 有没有办法在 Django 中控制来自网络摄像头的视频?

问题描述

我必须部署一个机器学习模型来处理来自用户相机的视频,我们必须处理模型的预测。我想让用户能够控制模型输入/从相机获取视频的时间,就像某种可以提供该服务的按钮一样。

目前,我能够对视频源进行预测,但它像每一帧一样是连续的,我正在使用 StreamingHttpResponse 将该帧返回到前端,但 StreamingHttpResponse 中的问题是我不知道如何包含应用程序中的任何控件(停止、继续预测)。

如果除了 StreamingHttpResponse 之外还有其他方法可以实现这一点,或者 StreamingHttpResponse 是否可行,我愿意接受建议 - 请指导我正确的方向

查看允许流式传输功能的函数

def gen(camera):
    while True:
        frame = cam.get_frame()
        # print(frame)
        m_image, lab =predict_video(frame, "result")
        print(lab)
        # m_image = cv2.cvtColor(m_image, cv2.COLOR_RGB2BGR)
        ret, m_image = cv2.imencode('.jpg', m_image)
        m_image = m_image.tobytes()
        yield(b'--frame\r\n'
              b'Content-Type: image/jpeg\r\n\r\n' + m_image + b'\r\n\r\n')


def livefeed(request):
    try:
        return StreamingHttpResponse(gen(VideoCamera()), content_type="multipart/x-mixed-replace;boundary=frame")
    except Exception as e:  # This is bad! replace it with proper handling
        print(e)

predict_video 是我在views.py 中编写的另一个函数,它返回修改后的图像(带有边界框的图像)和预测的标签。

cam 是我在另一个 .py 文件中定义的 VideoCamera 类的一个对象,它的定义是这样的:

class VideoCamera(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0)
        (self.grabbed, self.frame) = self.video.read()
        threading.Thread(target=self.update, args=()).start()

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

    def get_frame(self):
        image = self.frame
        # ret, jpeg = cv2.imencode('.jpg', image)
        return image

    def update(self):
        while True:
            (self.grabbed, self.frame) = self.video.read()

视频部分的 urls.py:

path('live/', views.livefeed, name="showlive"),

我在 html 的 img 标记中包含了指向“live/”网址的链接,如下所示:


<h3> This is the live feed </h3>
<img src="{% url 'live' %}">

标签: pythondjangoopencvcomputer-visionwebrtc

解决方案


正如您在评论中提到的,您需要每秒 30 帧的视频处理,您需要WebRTC从浏览器/移动设备获取用户相机视频帧并将它们发送到您的后端。
那里有各种 WebRTC 实现,但对于 Python,您可以使用aiortc

aiortc 是 Python 中用于 Web 实时通信 (WebRTC) 和对象实时通信 (ORTC) 的库。它建立在 Python 的标准异步 I/O 框架 asyncio 之上。

对于您想要实时处理视频的用opencv例,项目存储库中有一个确切的示例,请查看 aiortc 服务器示例

此示例说明使用浏览器建立音频、视频和数据通道。它还使用 OpenCV 对视频帧执行一些图像处理。

最后,如果您使用的是同步 Django(3 之前的任何内容),则将 Django 用于此服务是不可行的,您应该考虑使用异步框架,如,Django3或...FastAPIStarlette


推荐阅读