Alwaysthinking
Alwaysthinking

Reputation: 21

How do I make images render properly using Django Streaming HTTPS Response?

I wrote some code in Python which utilizes OpenCV (among other packages) to go through a selected video frame by frame, check whether the frame has a person or not (see here), and then return all the frames where a person was found.

The goal (for now) is to dynamically display these images in a web browser. I used this answer for guidance: How to stream an HttpResponse with Django

My code is below:

def stream_response(request):
    return StreamingHttpResponse(detect())

def detect():
    frame_count=0
    while(frame_count < num_frames):
        ret, frame = capture.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        image_pil=Image.fromarray(gray)
        response = HttpResponse(content_type="image/jpeg")
        image_pil.save(response, "JPEG")
        yield response
        yield ""*1024
        time.sleep(1)
        frame_count+=1

However, when I use the StreamingHTTPResponse feature in Django to yield a response (a method to implement a generator), the response I see in the browser is gibberish (see image below). enter image description here

When I use HTTPResponse to return a response, however, the image displays fine in the browser when directed to the appropriate port.

I've tried various tests, and still can't figure it out. My theory is that it might be due to the browser being unable to render the image in the given time, but I'm not sure...

Update: Ended up yielding HTML directly from Python for the prototype app. That did the trick for current purposes, but will re-explore this down the line.

Upvotes: 1

Views: 642

Answers (1)

Muhammad Tahir
Muhammad Tahir

Reputation: 5184

You need distributed task queue system like Celery. You can make your application in the way that

You main page (from where execution flow starts)

  1. Ask the user to upload a video

  2. Save this video file on server

  3. Add an entry against video in the database

  4. Call your detect asynchronous task with id of the video record and save the id of the task returned in the database against video record
  5. Redirect your user to a success page with video id

On the success page

  1. Show a success message
  2. Using javascript call a status web service with video id and update the page (load images dynamically) accordingly again and again until you receive status complete.

In the status web service

  1. Get task id using video id

  2. Check task status

  3. Get images from database using video id (images that your asynchronous task is putting in the database in the background)

  4. Return the status (whether completed or in progress) and list of images

Upvotes: 2

Related Questions