Video Streaming On Flask Server Using RPi - Hackster.io

Video Streaming On Flask Server Using RPi - Hackster.io - 图1

Video Streaming On Flask Server Using RPi - Hackster.io - 图2

×

Log inSign up

ProjectsProjectsNewsContestsEventsVideosWorkshopsLaunch

×

Embed the widget on your own site

Add the following snippet to your HTML:

[Video Streaming On Flask Server Using RPi - Hackster.io - 图3

Video Streaming On Flask Server Using RPi - Hackster.io - 图4

Live video streaming using RPi and RPi camera module in Flask server.

Read up about this project on ](https://prod.hackster-cdn.online/assets/hackster_logo_text-21b76ddd8e1fdebbdc3634afac217796f9101e956c0107d58a3adbd35d16badd.png#alt=) “Video Streaming On Flask Server Using RPi”)

Video Streaming On Flask Server Using RPi

Ruchir Sharma

19 15,688

19

Video Streaming On Flask Server Using RPi - Hackster.io - 图6

Ruchir Sharma

Published October 28, 2017 © GPL3+

Video Streaming On Flask Server Using RPi

Live video streaming using RPi and RPi camera module in Flask server.

BeginnerFull instructions provided3 hours15,739

Video Streaming On Flask Server Using RPi - Hackster.io - 图7

[

](https://www.hackster.io/workshops/ultra96)

Our Turbocharge Python w/ Ultra96 PYNQ course is now available. Buy it now!

Advertisement

Things used in this project

Hardware components

Video Streaming On Flask Server Using RPi - Hackster.io - 图8

Raspberry Pi 3 Model B

×

1

Video Streaming On Flask Server Using RPi - Hackster.io - 图9

Raspberry Pi Camera Module

×

1

Story

Live video streaming server using RPi

There are many ways to stream video to browsers, and each method has its benefits and disadvantages. The method that works well with the streaming feature of Flask is to stream a sequence of independent JPEG pictures. This is called Motion JPEG . This method has low latency, but quality is not the best, since JPEG compression is not very efficient for motion video.

1. Connect the camera module and enable it

First of all, with the Pi switched off, you’ll need to connect the Camera Module to the Raspberry Pi’s camera port.

Video Streaming On Flask Server Using RPi - Hackster.io - 图10

  • Start up the Pi.

  • Open the Raspberry Pi Configuration Tool from the main menu or by typing sudo raspi-config in terminal(ctrl+alt+t).

Video Streaming On Flask Server Using RPi - Hackster.io - 图11

  • Enable Camera and I2C

Video Streaming On Flask Server Using RPi - Hackster.io - 图12

2. How to install OpenCV (prefer to use less than 3)

OpenCV 2.4

Video Streaming On Flask Server Using RPi - Hackster.io - 图13

3. What is Flask

Flask is a micro framework for Python.Flask depends on two external libraries:

Jinja2 template engine and the Werkzeug WSGI toolkit. To install Flask use pip:

  1. pip install Flask

4. Program

If you are using separate directory for flask app then make sure python file and templates directory in same folder, HTML file should be in templates directory.

Video Streaming On Flask Server Using RPi - Hackster.io - 图14

Make an empty file (test.py):

  1. # import required modules
  2. from flask import Flask, render_template, Response
  3. import picamera
  4. import cv2
  5. import socket
  6. import io
  7. app = Flask(__name__)
  8. vc = cv2.VideoCapture(0)
  9. @app.route('/')
  10. def index():
  11. """Video streaming ."""
  12. return render_template('index.html')
  13. def gen():
  14. """Video streaming generator function."""
  15. while True:
  16. rval, frame = vc.read()
  17. cv2.imwrite('pic.jpg', frame)
  18. yield (b'--frame\r\n'
  19. b'Content-Type: image/jpeg\r\n\r\n' + open('pic.jpg', 'rb').read() + b'\r\n')
  20. @app.route('/video_feed')
  21. def video_feed():
  22. """Video streaming route. Put this in the src attribute of an img tag."""
  23. return Response(gen(),
  24. mimetype='multipart/x-mixed-replace; boundary=frame')
  25. if __name__ == '__main__':
  26. app.run(host='0.0.0.0', debug=True, threaded=True)

Video Streaming On Flask Server Using RPi - Hackster.io - 图15

Make another empty html file (index.html ):

  1. <html>
  2. <head>
  3. <title>Video Streaming </title>
  4. </head>
  5. <body>
  6. <h1> Live Video Streaming </h1>
  7. <img src="{{ url_for('video_feed') }}">
  8. </body>
  9. </html>

Video Streaming On Flask Server Using RPi - Hackster.io - 图16

The application has two routes. The / route serves the main page, which is defined in the index.html

The /video_feed route returns the streaming response. Because this stream returns the images that are to be displayed in the web page, the URL to this route is in the src attribute of the image tag. The browser will automatically keep the image element updated by displaying the stream of JPEG images in it.

You can also modify script to take snapshot from live video streaming.

Note

If you are not able to see the video streaming then install these. For streaming video ffpeg and uv4l1.

1. How to install uv4l ( User space Video4Linux)

To install Uv4l on Raspbian Wheezy add the following line to the file /etc/apt/sources.list :

  1. deb http://www.linux-projects.org/listing/uv4l_repo/raspbian/ wheezy main

On Raspbian Jessie add the following line to the file /etc/apt/sources.list :

  1. deb http://www.linux-projects.org/listing/uv4l_repo/raspbian/ jessie main
  2. sudo apt-get update
  3. sudo apt-get install uv4l uv4l-raspicam

If you want the driver to be loaded at boot, also install this optional package:

  1. sudo apt-get install uv4l-raspicam-extras

Apart from the driver for the Raspberry Pi Camera Board, the following Streaming Server front-end and drivers can be optionally installed:

  1. sudo apt-get install uv4l-server uv4l-uvc uv4l-xscreen uv4l-mjpegstream uv4l-dummy uv4l-raspidisp

If you are getting error in installing uv4l-server like required installer libssl1.0.0 is not present so to install that we have to add line to /etc/apt/sources.list

  1. deb http://ftp.de.debian.org/debian jessie main
  2. sudo apt-get update

The WebRTC extension for the Streaming Server is also available with two alternative packages depending on the Raspberry Pi model in use.

If you have a Raspberry Pi 1, Zero or Zero W (Wireless), type:

  1. sudo apt-get install uv4l-webrtc-armv6

For Raspberry Pi 2 or 3) type:

  1. sudo apt-get install uv4l-webrtc

To restart the server:

  1. sudo service uv4l_raspicam restart

It works on port 8080.

2. To install ffmpeg:

A_dd the following line to the file /etc/apt/sources.list:_

  1. deb http://www.deb-multimedia.org jessie main non-free

Update the list of available packages:

  1. sudo apt-get update

Install ffmpeg by command:

  1. sudo apt-get install ffmpeg

5. Output

Video Streaming On Flask Server Using RPi - Hackster.io - 图17

After modifying script:

Video Streaming On Flask Server Using RPi - Hackster.io - 图18

Video Streaming On Flask Server Using RPi - Hackster.io - 图19

Video Streaming On Flask Server Using RPi - Hackster.io - 图20

Read more)

Schematics

Camera-RPi connection

Video Streaming On Flask Server Using RPi - Hackster.io - 图21

Code

main file

Python

!/usr/bin/env python from flask import Flask, rendertemplate, Response import picamera import cv2 import socket import io app = Flask(_name) vc = cv2.VideoCapture(0) @app.route(‘/‘) def index():

“””Video streaming””” return rendertemplate(‘index.html’) def gen():
“””Video streaming generator function.””” while True: rval, frame = vc.read() cv2.imwrite(‘t.jpg’, frame) yield (b’—frame\r\n’ b’Content-Type: image/jpeg\r\n\r\n’ + open(‘t.jpg’, ‘rb’).read() + b’\r\n’) @app.route(‘/videofeed’) def videofeed():
“””Video streaming route. Put this in the src attribute of an img tag.””” return Response(gen(), mimetype=’multipart/x-mixed-replace; boundary=frame’) if _name
== ‘__main
‘:
app.run(host=’0.0.0.0’, debug=True, threaded=True)

index.html

HTML


Live Video Streaming

Video Streaming On Flask Server Using RPi - Hackster.io - 图22

Credits

Video Streaming On Flask Server Using RPi - Hackster.io - 图23

Ruchir Sharma

8 projects • 127 followers

Follow ContactContact

Comments

Please log in;) or sign up;) to comment.

Video Streaming On Flask Server Using RPi - Hackster.io - 图24

James

2 years ago

Nice beginner project! My only question is how to restart the stream once you close it?

Video Streaming On Flask Server Using RPi - Hackster.io - 图25

Ruchir Sharma

2 years ago

sudo service uv4l_raspicam restart

Video Streaming On Flask Server Using RPi - Hackster.io - 图26

James

2 years ago

thanks! Also will it work with opencv3?

Video Streaming On Flask Server Using RPi - Hackster.io - 图27

Ruchir Sharma

2 years ago

I have not tried it with opencv3 but it should work.

Video Streaming On Flask Server Using RPi - Hackster.io - 图28

Kevin

2 years ago

This comment has been deleted.

Video Streaming On Flask Server Using RPi - Hackster.io - 图29

Ruchir Sharma

2 years ago

with picamera.PiCamera() as camera:
camera.resolution = (1024, 768)

Video Streaming On Flask Server Using RPi - Hackster.io - 图30

Ruchir Sharma

2 years ago

Welcome man !!!

Video Streaming On Flask Server Using RPi - Hackster.io - 图31

Tidus Baey

2 years ago

Hi Ruchir

I saw you have a login page for the stream. I had also tried to add login function for the raspicam live stream but I had an error I cant logout and my camera still on when I try logging out

Video Streaming On Flask Server Using RPi - Hackster.io - 图32

Ruchir Sharma

2 years ago

Hi Tidus,

Tell me one thing are you using any background image on video page.

Video Streaming On Flask Server Using RPi - Hackster.io - 图33

Yusuf Çağrı Daşkın

2 years ago

Hello,

First, you don’t need to save every frame. Saving and replacing every frame in a loop is a terrible idea for SD cards. Instead you can use a global variable on memory to hold the frame data. It will be better like this:

def gen():
“””Video streaming generator function.”””
while True:
rval, frame = vc.read()
byteArray = cv2.imencode(‘.jpg’, frame)[1].tobytes()
yield (b’—frame\r\n’
b’Content-Type: image/jpeg\r\n\r\n’ + byteArray + b’\r\n’)

Second, in this way you can make only one request at a time. When you make second request application will not response.

  • 1 thank

[

Video Streaming On Flask Server Using RPi - Hackster.io - 图34

](https://www.hackster.io/workshops/ultra96)

Our Turbocharge Python w/ Ultra96 PYNQ course is now available. Buy it now!

Advertisement

Related channels and tags

Related projects

[

Video Streaming On Flask Server Using RPi - Hackster.io - 图37

](/mjrobot/video-streaming-web-server-ef11e3)Video Streaming Web Server

[

Video Streaming On Flask Server Using RPi - Hackster.io - 图38

](/narender-singh/portable-video-streaming-camera-with-raspberry-pi-zero-w-dc22fd)Portable Video Streaming Camera with Raspberry Pi Zero W

[

Video Streaming On Flask Server Using RPi - Hackster.io - 图39

](/sssv/raspberry-pi-live-camera-streaming-70bbaf)Raspberry Pi Live Camera Streaming

[

Video Streaming On Flask Server Using RPi - Hackster.io - 图40

](/fabolandry/raspberry-pi-ip-cam-aws-and-hls-streaming-b449e7)Raspberry Pi IP Cam AWS and HLS Streaming

[

Video Streaming On Flask Server Using RPi - Hackster.io - 图41

](/maciek85/raspberry-pi-video-preview-in-the-browser-ebe576)Raspberry Pi Video Preview in the Browser

View more related projects

Similar projects you might like

[

Recognize digits with Raspberry Pi, Pi Camera, OpenCV, and TensorFlow.

](/dhq/ai-digit-recognition-with-picamera-2c017f)

AI Digit Recognition with PiCamera

Dimiter Kendri

4311K

[

This is a trail camera that will notify you using a cellular network that there has been activity nearby.

](/cybermah/trail-camera-e1deff)

Trail Camera

Dana Mah

3712K

[

MATRIX Voice ESP32 standalone satellite mics for a Raspberry Pi server running Snips. Credit to Paul Romkes for this amazing project!

](/matrix-labs/esp32-matrix-voice-satellites-streaming-audio-to-pi-server-63b9cd)

ESP32 MATRIX Voice Satellites Streaming Audio to Pi Server

Team MATRIX Labs

299.8K

[

An easy way to know if someone is at the door and take picture of that person.

](/NikunjME/raspberry-pi-security-camera-system-with-notification-b39d00)

Raspberry Pi Security Camera System with Notification

Nikunj Patel

246.8K

[

I created a Raspberry Pi face recognizer, which alarms me when somebody sits in front of my computer.

](/vuleticnenad/rpi-computer-alarm-with-face-recognition-9533ca)

RPi Computer Alarm with Face Recognition

Nenad Vuletic

10894

[

So to preface the story let me explain. I own a computer store where I repair computers, and other electronics and sell electronics.

](/MakrToolbox/pi-outdoor-timelapse-server-2b8a65)

Pi Outdoor Timelapse Server

MakrToolbox

61.2K

[

Detecting motion with PIR sensor and sending the Raspberry Pi camera image as email.

](/ujur007/raspberry-pi-home-security-system-with-camera-and-pir-sensor-6154f3)

Raspberry Pi Home Security System with Camera and PIR Sensor

ujjval rathod

5024K

[

Stream videos (and other media) to mobile devices/tables while on the go. Great for streaming video to iPads in a car on a long road trip!

](/bilbo007/portable-media-server-and-access-point-00f272)

Portable media server and access point

Heinrich Vermeulen

3922K

Video Streaming On Flask Server Using RPi - Hackster.io - 图42

1

Video Streaming On Flask Server Using RPi - Hackster.io - 图43

2

Video Streaming On Flask Server Using RPi - Hackster.io - 图44

3

You’re on your last one! Sign up to access unlimited projects featuring Photos & Video and more.

Sign upNot now;)

19

  • More cool stuff