簡體   English   中英

Opencv Django網頁中攝像頭直播Stream

[英]Opencv Live Stream from camera in Django Webpage

我正在 Django 做一個項目。我想在網頁上顯示來自攝像頭的實時提要。 但我不確定如何返回我從 web 頁面上的攝像頭獲得的實時提要。 這是我到目前為止嘗試過但沒有看到任何進展的代碼。

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})

上述問題的解決方案是這樣的:

視圖.py

from django.views.decorators import gzip
from django.http import StreamingHttpResponse
import cv2
import threading

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
        _, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()

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


def gen(camera):
    while True:
        frame = camera.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:
        cam = VideoCamera()
        return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame")
    except:  # This is bad! replace it with proper handling
        pass

然后在 urls.py 中將其映射到一個 url。

我修改了 Aniket Maithani 的代碼以在某些 img 源中顯示它。

相機.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
        _, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()

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

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

視圖.py

from camera import *

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

def index(request, *args, **kwargs):
    return render(request, 'index.html')

網址.py

from django.urls import path
from .views import *

urlpatterns = [
    path('', index),

        # 'livefe' -> function from views
        # 'live_camera' -> name at index.html>img src="{% url 'live_camera' %}
        path('/camera', livefe, name="live_camera"),
    ]

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebCamera</title>
</head>
<body>
    <div>
        <img src="{% url 'live_camera' %}">
    </div>
</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM