12

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})
Aniket Maithani
  • 845
  • 1
  • 10
  • 24

2 Answers2

25

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.

Sayyor Y
  • 1,130
  • 2
  • 14
  • 27
Aniket Maithani
  • 845
  • 1
  • 10
  • 24
  • 1
    The above code works fine. Can you please tell me how can I modify this code such that it reads the frames from camera but it need not display the frame on screen. Basically, I want to read the camera input and not display it to the user on screen. – Abhijit Oct 15 '18 at 10:28
  • thanks for the solution. I have one query related to this. This solution displays images on the whole web page and it keeps reloading. I need to update certain div or image source with the camera live feed. Please help. I was asking if it can be done using context as we pass context in render in views.py – Anshuman Singh Apr 23 '19 at 11:19
  • @anshumansingh this was a quick hack though. Will look into a better solution soon. – Aniket Maithani Apr 23 '19 at 13:18
  • @AniketMaithani I found one solution. I have exposed one url to this live video feed and then set this url as source to the image and it works fine. I tried extracting the content from StreamingHttpResponse but could not. If you have any better solution, please share. – Anshuman Singh Apr 24 '19 at 05:36
  • @AniketMaithani, I would like to try your code but since I am new in django and python, did you have any reference that I could read to do your code. I have tried to follow some articles, but I still confused when adding code in html – wahyu Mar 31 '21 at 01:32
  • I am trying this on a server with a local webcam but it's looking for a connected webcam. Does this only work on localhost or is there any way to use a local webcam with Django on a server? – Rob Michiels May 27 '21 at 14:39
1

I modified the code by Aniket Maithani to display it in certain img source.

camera.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')

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

urls.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>
Bianca Emi
  • 31
  • 3