Showing a rtsp stream on React Frontend

Viewed 1069

I need to show a video stream on a react component with a Python+Django backend.

CURRENT SITUATION:

I'm using opencv library to get the stream:

import cv2
[...]
def read_data():
  cap = cv2.VideoCapture("rtsp://user:password/bla bla bla")
  while(cap.isOpened()):
    ret, frame              = cap.read()
    retval, buffer          = cv2.imencode('.jpg', frame)
    image_result_base64     = base64.b64encode(buffer)
    return HttpResponse(image_result_base64, 200)

On React, where this.state.response_data is the content responseText of the backend call:

render ()
{
  const img_data ="data:image/png;base64," + this.state.response_data;
  return <img id="overView" class="overView" alt="Stream" src={ img_data}  width="90%" />
}

This approach works and on frontend I see the frame in my component.

Unfortunally to create some sort of stream, I need to call backend at least 10 times every second to have 10fps. This is heavy to backend.

I read about StreamingHttpResponse but I don't know if fits my needs.

1 Answers

Using StreamingHttpResponse,

In Django,

import cv2
from django.http import StreamingHttpResponse

def gen(camera):
    video = cv2.VideoCapture()
    video.open(camera)
    print("streaming live feed of ",camera)
    while True:
        success, frame = video.read()  
        if not success:
            break
        else:
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--frame\r\n'
                b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

#url:"localhost:8000/camera_feed"
def camerafeed(request): 
    return StreamingHttpResponse(gen("rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"),content_type="multipart/x-mixed-replace;boundary=frame")

In the frontend,

<img src="localhost:8000/camera_feed"></img>

I don't know if this is any better... But it works!

Related