Django网页中来自摄像头的Opencv Live Stream [英] Opencv Live Stream from camera in Django Webpage

查看:965
本文介绍了Django网页中来自摄像头的Opencv Live Stream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Django创建一个项目.我想在网页上显示来自摄像机的实时供稿.但是我不确定如何返回从网页上的摄像头获取的实时供稿. 到目前为止,这是我尝试过的代码,但未见任何进展.

I am making a project in Django. And I want to show live feed from camera on a webpage. But I am not sure on how to return live feed I get from a cam on a web page. Here's my code that I have tried so far but haven't seen any progress.

from django.shortcuts import render
from .forms import FaceAdditionForm
import cv2
import numpy as np
from django.http import StreamingHttpResponse

def capture_video_from_cam():
    cap = cv2.VideoCapture(0)
    currentFrame = 0
    while True:

        ret, frame = cap.read()

        # Handles the mirroring of the current frame
        frame = cv2.flip(frame,1)
        currentFrame += 1

def addfaces(request):
    add_faces_form = FaceAdditionForm()
    if add_faces_form.is_valid():
        add_faces_form.save()
    return render(request, 'base.html', {'add_faces': add_faces_form})


def show_video_on_page(request):
    resp = StreamingHttpResponse(capture_video_from_cam())
    return render(request, 'base.html', {'video': resp})

推荐答案

上述问题的解决方案如下:

The solution for the above problem was something like this :

views.py

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 jpeg.tobytes()

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


cam = VideoCamera()


def gen(camera):
    while True:
        frame = cam.get_frame()
        yield(b'--frame\r\n'
              b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')


@gzip.gzip_page
def livefe(request):
    try:
        return StreamingHttpResponse(gen(VideoCamera()), content_type="multipart/x-mixed-replace;boundary=frame")
    except:  # This is bad! replace it with proper handling
        pass

然后在urls.py中将此映射到一个url.

And then in urls.py map this to a url.

这篇关于Django网页中来自摄像头的Opencv Live Stream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆