[Django]-Passing a cv2 frame from view to template

6๐Ÿ‘

โœ…

I would suggest base64 encoding the frame and passing that string. That way you can pass the dynamically generated image from the views to the result.html to render. You can then display the base64 image in the result.html.

views.py

import cv2
import base64

def index(request):
  #while (True): #Note: This loop is pointless, it will break when you return.

    #video_capture = cv2.VideoCapture(0)
    #ret, frame = video_capture.read()

    img = "D:/Desktop/Tap/bsnsFaces.jpg"
    frame = cv2.imread(img)
    ret, frame_buff = cv2.imencode('.jpg', frame) #could be png, update html as well
    frame_b64 = base64.b64encode(frame_buff)
    facesNumber ="Found {0} faces!".format(len(faces))

    # Note this was fixed to be one dict with the context variables
    return render(request, 'result.html', {'p': facesNumber, 'img': frame_b64})

result.html

   <img src="data:image/jpeg;base64, {{img}}"></img>

Just a note based on your while loop, if you want to be updating the page constantly from the webcam, this should be done clientside. Otherwise you will need to be constantly refreshing the page to see image updates. The client (result.html) can poll the server with AJAX for image updates, and refresh itself without actually reloading the entire result.html page.

๐Ÿ‘คTheoretiCAL

Leave a comment