Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opencv Live Stream from camera in Django Webpage

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})
like image 223
Aniket Maithani Avatar asked Apr 05 '18 19:04

Aniket Maithani


People also ask

Can we use OpenCV in Django?

Originally Answered: Is it possible to use Python with its OpenCV library on a web app made with Django ? Yes, you can.

Is Django good for video streaming?

Core Django isn't suitable for the actual streaming of data. It currently is built around the request-response cycle of a typical http transaction. You could build your website around the streaming protocols using Django, but to do the actual streaming, you would need to use a different component.


Video Answer


1 Answers

The solution for the above problem was something like this :

views.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

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

like image 174
Aniket Maithani Avatar answered Sep 29 '22 01:09

Aniket Maithani