Reading MJPEG stream from Flask server with OpenCV (Python) Reading MJPEG stream from Flask server with OpenCV (Python) flask flask

Reading MJPEG stream from Flask server with OpenCV (Python)


Changing the frame generator worked for me:

yield (b'--frame\r\n'       b'Content-Type:image/jpeg\r\n'       b'Content-Length: ' + f"{len(frame)}".encode() + b'\r\n'       b'\r\n' + frame + b'\r\n')


For Anabad (And others):

Oof, it's been a while for this problem. If I remember correctly, the short answer is: NO, I was never able to get this to work properly.

The camera is accessed by multiple programs this way at the same time (when a request is send to the API more than once, multiple threads start reading the camera) which the camera cannot handle. The best way to handle this properly (in my opinion), is to read the camera in a separate class on it's own thread, and use a observer pattern for the API. Every time a new request comes in from a client to read the camera, an observer will send the new frames once they become available.

This solves the problem of the camera being accessed by multiple class instances/threads, which is the reason why this would not work.Get around this problem and it should work fine.


Maybe it's too late to answer, but I got the same issue and found a solution.

The error [mpjpeg @ 0000017a86f524a0] Expected boundary '--' not found, instead found a line of 82 bytes is error message from ffmpeg which OpenCV uses as a mjpeg image decoder as a backend.

It means images are streamed as mpjpeg (= multipart jpeg data), but the boundary that separates each jpeg image is not found (so the decoder cannot decode the image).

The boundary should starts with --, however the server written in the question declares that the boundary is just frame here: mimetype='multipart/x-mixed-replace; boundary=frame')This part should be like mimetype='multipart/x-mixed-replace; boundary=--frame')

Also I found that line separation between boundary and image data is mandatory.(since ffmpeg provided by Ubuntu 18.04 and later?)Please see another implementation of mjpg server. ( https://github.com/ros-drivers/video_stream_opencv/blob/e6ab82a88dca53172dc2d892cd3decd98660c447/test/mjpg_server.py#L75 )

Hope it will help.