How to redraw opencv frame with django frame in real time?

I'm trying to use a Raspberry Pi to capture an image from a USB camera and cast it using the Django Framework. I tried to use StreamingHttpResponse to stream a frame from Opencv2. However, it just shows 1 frame and does not replace the image.

How can I replace the image in real time?

Here is my code

from django.shortcuts import render from django.http import HttpResponse,StreamingHttpResponse import cv2 import time class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): ret,image = self.video.read() ret,jpeg = cv2.imencode('.jpg',image) return jpeg.tobytes() def gen(camera): while True: frame = camera.get_frame() yield(frame) time.sleep(1) def index(request): # response = HttpResponse(gen(VideoCamera()) return StreamingHttpResponse(gen(VideoCamera()),content_type="image/jpeg") 
+7
source share
1 answer

@Ritwick. I did this by changing the gen and index function below

  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 index (request): 
     try:
         return StreamingHttpResponse (gen (VideoCamera ()), content_type = "multipart / x-mixed-replace; boundary = frame")
     except HttpResponseServerError as e:
         print ("aborted")

I use a python generator to generate each frame of the camera and using StreamingHttpResponse to replace multipart / x-mixed-replace , which is marked as a frame

In django there is a gzip decorator function.

  from django.views.decorators import gzip 

To increase the speed of streaming. I used the dzango gzip decorator method for the gzip frame.

+1
source

Source: https://habr.com/ru/post/1271271/


All Articles