- Embed the widget on your own site
- Video Streaming On Flask Server Using RPi
- !/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():
- Credits
- Comments
- Similar projects you might like
Video Streaming On Flask Server Using RPi - Hackster.io
×
ProjectsProjectsNewsContestsEventsVideosWorkshopsLaunch
×
Embed the widget on your own site
Add the following snippet to your HTML:
[
Live video streaming using RPi and RPi camera module in Flask server.
Read up about this project on “Video Streaming On Flask Server Using RPi”)
Video Streaming On Flask Server Using RPi
19 15,688
19
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
[
](https://www.hackster.io/workshops/ultra96)
Our Turbocharge Python w/ Ultra96 PYNQ course is now available. Buy it now!
Things used in this project
Hardware components
×
1
×
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.
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).
- Enable Camera and I2C
2. How to install OpenCV (prefer to use less than 3)
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:
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.
Make an empty file (test.py):
# import required modules
from flask import Flask, render_template, Response
import picamera
import cv2
import socket
import io
app = Flask(__name__)
vc = cv2.VideoCapture(0)
@app.route('/')
def index():
"""Video streaming ."""
return render_template('index.html')
def gen():
"""Video streaming generator function."""
while True:
rval, frame = vc.read()
cv2.imwrite('pic.jpg', frame)
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + open('pic.jpg', 'rb').read() + b'\r\n')
@app.route('/video_feed')
def video_feed():
"""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)
Make another empty html file (index.html ):
<html>
<head>
<title>Video Streaming </title>
</head>
<body>
<h1> Live Video Streaming </h1>
<img src="{{ url_for('video_feed') }}">
</body>
</html>
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 :
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 :
deb http://www.linux-projects.org/listing/uv4l_repo/raspbian/ jessie main
sudo apt-get update
sudo apt-get install uv4l uv4l-raspicam
If you want the driver to be loaded at boot, also install this optional package:
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:
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
deb http://ftp.de.debian.org/debian jessie main
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:
sudo apt-get install uv4l-webrtc-armv6
For Raspberry Pi 2 or 3) type:
sudo apt-get install uv4l-webrtc
To restart the server:
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:_
deb http://www.deb-multimedia.org jessie main non-free
Update the list of available packages:
sudo apt-get update
Install ffmpeg by command:
sudo apt-get install ffmpeg
5. Output
After modifying script:
Schematics
Camera-RPi connection
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
Credits
Ruchir Sharma
8 projects • 127 followers
Comments
Please log in;) or sign up;) to comment.
James
2 years ago
Nice beginner project! My only question is how to restart the stream once you close it?
Ruchir Sharma
2 years ago
sudo service uv4l_raspicam restart
James
2 years ago
thanks! Also will it work with opencv3?
Ruchir Sharma
2 years ago
I have not tried it with opencv3 but it should work.
Kevin
2 years ago
This comment has been deleted.
Ruchir Sharma
2 years ago
with picamera.PiCamera() as camera:
camera.resolution = (1024, 768)
Ruchir Sharma
2 years ago
Welcome man !!!
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
Ruchir Sharma
2 years ago
Hi Tidus,
Tell me one thing are you using any background image on video page.
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
[
](https://www.hackster.io/workshops/ultra96)
Our Turbocharge Python w/ Ultra96 PYNQ course is now available. Buy it now!
Related channels and tags
Related projects
[
](/mjrobot/video-streaming-web-server-ef11e3)Video Streaming Web Server
[
](/narender-singh/portable-video-streaming-camera-with-raspberry-pi-zero-w-dc22fd)Portable Video Streaming Camera with Raspberry Pi Zero W
[
](/sssv/raspberry-pi-live-camera-streaming-70bbaf)Raspberry Pi Live Camera Streaming
[
](/fabolandry/raspberry-pi-ip-cam-aws-and-hls-streaming-b449e7)Raspberry Pi IP Cam AWS and HLS Streaming
[
](/maciek85/raspberry-pi-video-preview-in-the-browser-ebe576)Raspberry Pi Video Preview in the Browser
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
4311K
[
This is a trail camera that will notify you using a cellular network that there has been activity nearby.
](/cybermah/trail-camera-e1deff)
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
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
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)
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
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
3922K
1
2
3
You’re on your last one! Sign up to access unlimited projects featuring Photos & Video and more.
Sign upNot now;)
19