Capture and stream video on browser with Python-FLASK

Photo by Diva Plavalaguna: (pexels.com)

Section 1 — Application architecture

The Flask application creates a route for the homepage (‘/’), which calls the “stream” function.
The “stream” function returns a generator object which captures video frames using the VideoCapture function from OpenCV library.
The frames are then encoded using the imencode function from OpenCV library, and converted to bytes using the tobytes() method. The stream of bytes is sent to the client as a multipart/x-mixed-replace response.

Section 2 — Code

Section 3 — Code explanation

The code uses the Flask web framework to create a web server that serves a video stream from the default camera (cv2.VideoCapture(0)) on the local machine. The video stream is served using the Multipart/x-mixed-replace content type, which allows the client’s browser to dynamically update the content of the page as new frames are received.
Here's a brief overview of how the code works:

  1. The Flask module is imported, as well as the cv2 module (OpenCV) which is used to capture the video frames.
  2. An instance of the Flask class is created, and a route is defined for the root URL (‘/’)
  3. The stream() function is defined, which returns a Response object containing the video stream generated by the gen() function.
  4. The gen() function captures video frames from the default camera using the cv2.VideoCapture() function and encodes them as JPEGs using cv2.imencode().
  5. The encoded frames are then yield to the client as a multipart HTTP response.
  6. In the last line of the code, the script starts a local development server on IP address 127.0.0.4 and port 5000, which will serve the video stream to any client that connects to it.

Run this code, and then connect to the server using a web browser by going to the IP address and port specified in the app.run() function (http://127.0.0.4:5000/).

--

--

Automation Engineer | https://shelwyn.in/ | Currently in Bengaluru

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store