In this post we’re going to show you how you can do video streaming with a Raspberry Pi and a Raspberry Pi Camera – how to stream live video into a web page that you can access in any device that has a browser and is connected to the same network the Pi is. This is useful to apply to a home surveillance camera, for example.
Prerequisites:
- You should already be familiar with the Raspberry Pi board – read Getting Started with Raspberry Pi
- You should have the Raspbian or Raspbian Lite operating system installed in your Raspberry Pi
- You can read this post for an introduction to the Raspberry Pi Camera V2 module
Enable the Rasperry Pi Camera Module
If you’re using the Raspberry Pi Camera Module, you need to enable the camera software in your Raspberry Pi in order to use it. In the Desktop environment, go to the Raspberry Pi Configuration window under the Preferences menu, open the Interfaces tab and enable the Camera as shown in figure below.
Or, in the Terminal window, type the following command:
pi@raspberry:~ $ sudo raspi-config
You should see the Raspberry Pi software configuration tool. Select the Interfacing Options:
Enable the camera and reboot your Pi:
Find the Raspberry Pi IP address
To access your video streaming web server, you need to know your Raspberry Pi IP address. For that, use the following command:
pi@raspberry:~ $ ifconfig
You’ll be given a bunch of information, including your Raspberry Pi IP address. In my case, the RPi IP address is 192.168.1.112.
Connect the camera
Connecting the Raspberry Pi Camera Module is easy. With the Pi shutdown, connect the camera to the Pi CSI port as shown in the following figure. Make sure the camera is connected in the right orientation with the ribbon blue letters facing up as shown in the next figure.
Writing the script
The script for video streaming is shown below. You can find this script at the official PiCamera package documentation.
Create a new file called rpi_camera_surveillance_system.py:
pi@raspberrypi:~ $ nano rpi_camera_surveillance_system.py
Copy the following code to your newly created file:
# Web streaming example
# Source code from the official PiCamera package
# http://picamera.readthedocs.io/en/latest/recipes2.html#web-streaming
import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server
PAGE="""\
<html>
<head>
<title>Raspberry Pi - Surveillance Camera</title>
</head>
<body>
<center><h1>Raspberry Pi - Surveillance Camera</h1></center>
<center><img src="stream.mjpg" width="640" height="480"></center>
</body>
</html>
"""
class StreamingOutput(object):
def __init__(self):
self.frame = None
self.buffer = io.BytesIO()
self.condition = Condition()
def write(self, buf):
if buf.startswith(b'\xff\xd8'):
# New frame, copy the existing buffer's content and notify all
# clients it's available
self.buffer.truncate()
with self.condition:
self.frame = self.buffer.getvalue()
self.condition.notify_all()
self.buffer.seek(0)
return self.buffer.write(buf)
class StreamingHandler(server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(301)
self.send_header('Location', '/index.html')
self.end_headers()
elif self.path == '/index.html':
content = PAGE.encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('Content-Length', len(content))
self.end_headers()
self.wfile.write(content)
elif self.path == '/stream.mjpg':
self.send_response(200)
self.send_header('Age', 0)
self.send_header('Cache-Control', 'no-cache, private')
self.send_header('Pragma', 'no-cache')
self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
self.end_headers()
try:
while True:
with output.condition:
output.condition.wait()
frame = output.frame
self.wfile.write(b'--FRAME\r\n')
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-Length', len(frame))
self.end_headers()
self.wfile.write(frame)
self.wfile.write(b'\r\n')
except Exception as e:
logging.warning(
'Removed streaming client %s: %s',
self.client_address, str(e))
else:
self.send_error(404)
self.end_headers()
class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
allow_reuse_address = True
daemon_threads = True
with picamera.PiCamera(resolution='640x480', framerate=24) as camera:
output = StreamingOutput()
#Uncomment the next line to change your Pi's Camera rotation (in degrees)
#camera.rotation = 90
camera.start_recording(output, format='mjpeg')
try:
address = ('', 8000)
server = StreamingServer(address, StreamingHandler)
server.serve_forever()
finally:
camera.stop_recording()
To save your file press Ctrl+X, type Y and Enter.
Accessing the video streaming
After writing the scrip, you can run it using Python 3. Run the next command:
pi@raspberrypi:~ $ python3 rpi_camera_surveillance_system.py
Once the script is running, you can access your video streaming web server at: http://<Your_Pi_IP_Address>:8000. Replace with your own Raspberry Pi IP address, in my case http://192.168.1.112:8000.
You can access the video streaming through any device that has a browser and is connected to the same network that your Pi.
You can use your Pi to monitor your home as a surveillance camera:
Wrapping up
I hope this project was useful! You could easily upgrade this home surveillance device to record video or notify you when motion is detected.
We also have a project on how to build a complete CCTV system with the Raspberry Pi using MotionEyeOS. Feel free to take a look.
Like home automation? Learn more about Node-RED, Raspberry Pi, ESP8266 and Arduino with my course: Build a Home Automation System for $100.
Do you have any questions? Leave a comment down below!
Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.
excellent tutorial! I have it running since about a couple of minutes… and it works fine. Thanks!
Hi André.
We’re glad it works!
Thanks for your support.
Regards
Sara 🙂
thanks for all.
i have a question if possible.
who can i send video for 200m to my ipade of my smartphone please
thank you very much for this tutorial
Thanks for your support! 🙂
Hi Sara,
I am contacting you in regards to your “Video Streaming with Raspberry Pi Camera”. Article.
How can I stream and objects’ detection video? At the moment I can only see this through the HDMI output of the Raspberry pi.
Could you help? I can supply the code for a better reference
Thanks!!!
Excellent article guiding the new builder . I successfully built the project at one attempt and monitoring my house.
Thank you
Hi!Thank you!
We’re glad it worked! 🙂
hi
I would save video in 2hours in this code python
what should I do???????????
Hi.
This code is not prepared to record video.
You can take a look at this section “Recording video into a file” in this blog post
https://randomnerdtutorials.com/guide-to-raspberry-pi-camera-v2-module/
Great video for learning and making projects. I have one question regarding this, how to save the video and capture the image while streaming live?
you have put it in aloop like
while true:
…………………..your code
sleep(x)//in seconds
Exceptionally easy. I have this running on a Raspberry Pi Zero w/ Wifi, it will be installed into a Pine Wood Derby Car to stream its run live to a computer set up during the race. I think the scouts are going to love this. What is even cooler, is that the car will be within the 5 oz needed to race! Even better, there is very little Lag on the fed. I am very impressed!!!!
Can you please guide me as to how I’d make a separate html file, in the code the html code is written with the python code. I want to add style.css so I can make my website cool. I’ve been trying myself but I can not link the html file with the py file
Hi. I’ll suggest something, but I’m not sure if it will work. I haven’t tested this method with this example. I’ve only tested using Python. It worked fine.
– Create your html text in a separated file. For example test.html. The file should be located on the same folder that your python script.
– Then, in your Python code, read the content of the html file and save it into the PAGE variable (which is the variable that contains the html content in the code). Here’s a snippet example that reads the content of a file and saves it in the text variable.
file = open(‘test.html’, ‘r’)
text = file.read().strip()
file.close()
I hope this helps.
This looks great, about to try it on my pi, but what about a password? Because if I have this monitoring my home, will someone with a password be able to see my live feed?
Hi.
This example doesn’t have a password. So, anyone inside your network that accesses the Raspberry Pi IP address can see your footage.
There are ways to add a password to your streaming server, but we don’t have any tutorial on that subject at the moment 🙁
If you want to build a more professional monitoring video streaming, I recommend using MotionEye, in which you can monitor several cameras at the same time, and it requires an authentication. We have tutorials about that:
– CCTV Raspberry Pi Based System with Storage using MotionEyeOS
– Install MotionEyeOS on Raspberry Pi – Surveillance Camera System
I hope this helps.
Regards,
Sara 🙂
Thanks
Works perfectly.
Thanks Adam! I’m glad it worked for you 🙂
Thanks. Simplest option and worked the first time.
Great tutorial! I used it and it worked like a charm.
Can you recommend how can I stream audio as well? I have a USB Microphone, how can I also stream audio over HTTP?
I’m glad it worked. Unfortunately I don’t have any example about that at the moment… Regards,
Rui
hello,
It works for me but for a short time. After that message WARNING:root:Removed streaming client and the camera stops working
any idea ?
I have the same problem, somebody find a solution ?
Hi i’m South Korea student
I am so appriciate for you content!
Owing to you, I can finish my senior project perfectfully!
Speclially,
i doesn’t know that how can connect python with http.
God bless you!!!
Thank you!
Hi, great tutorial for Streaming, I want to be able to view it remotely when connected to another network, for example, if I have it set up at home and want to view it at work, any recommendations on how I would go about doing this using this script. Thanks in advance.
Hi Pedro.
The best way to do that is using MotionEyeOS.
It allows you to configure several settings to build a surveillance system.
– https://randomnerdtutorials.com/install-motioneyeos-on-raspberry-pi-surveillance-camera-system/
– https://randomnerdtutorials.com/cctv-raspberry-pi-based-system-storage-motioneyeos/
No, MotionEyeOS, and even MotionEye (without OS) is obsolete, not working anymore, unless you downgrade to old software/hardware.
And the scipt in the artical, likwise, not working on the new stuff.
It did not work for me. It shows,
mmal: mmal_vc_port_enable: failed to enable port vc.null_sink:in:0(OPQV): ENOSPC
mmal: mmal_port_enable: failed to enable connected port (vc.null_sink:in:0(OPQV))0x14e95e0 (ENOSPC)
mmal: mmal_connection_enable: output port couldn’t be enabled
Traceback (most recent call last):
File “rpi_camera_surveillance_system.py”, line 84, in
with picamera.PiCamera(resolution=’640×480′, framerate=24) as camera:
File “/usr/lib/python3/dist-packages/picamera/camera.py”, line 433, in __init__
self._init_preview()
File “/usr/lib/python3/dist-packages/picamera/camera.py”, line 513, in _init_preview
self, self._camera.outputs[self.CAMERA_PREVIEW_PORT])
File “/usr/lib/python3/dist-packages/picamera/renderers.py”, line 558, in __init__
self.renderer.inputs[0].connect(source).enable()
File “/usr/lib/python3/dist-packages/picamera/mmalobj.py”, line 2212, in enable
prefix=”Failed to enable connection”)
File “/usr/lib/python3/dist-packages/picamera/exc.py”, line 184, in mmal_check
raise PiCameraMMALError(status, prefix)
picamera.exc.PiCameraMMALError: Failed to enable connection: Out of resources
Hi Gerald.
I’m sorry for taking so long to get back to you.
I was trying to find an answer to your question.
Accordingly to this discussion: github.com/waveform80/picamera/issues/488
It seems that your camera is already being used on the background.
You need to close the camera instance by using: camera.close()
Take a look at this link, I think this may be the solution:
raspberrypi.org/forums/viewtopic.php?t=155304
Then, to prevent this from happening again, I suggest adding the camera.close() at the end of the camera streaming script.
I hope this helps.
Regards,
Sara 🙂
I would like to command a robot via buttons that I want to insert in the html page, how can I do?
Hi Rossano.
Which board do you want to use to build the robot? Raspberry Pi?
We have a tutorial on how to control LEDs using Flask on a Raspberry Pi. That allows you to insert buttons and perform different actions depending on the request URL.
Here’s the tutorial: Raspberry Pi Web Server using Flask to Control GPIOs
The example shows how to control LEDs, but you can easily control a DC motor using the gpiozero library for raspberry pi: gpiozero.readthedocs.io/en/stable/api_output.html?highlight=motor#motor
I hope this helps.
Regards,
Sara 🙂
Great script – how do I rotate 180 degrees or flip the output in the code?
Hi.
Just add the following line to your code:
camera.rotation = 180
On line 87: github.com/RuiSantosdotme/Random-Nerd-Tutorials/blob/master/Projects/rpi_camera_surveillance_system.py
Regards,
Sara 🙂
Running the Python script, I get the following error.
It would be nice if you could give me a hint what to do.
pi@Schuur-PiZero:~/webcam $ sudo python3 rpi_camera_surveillance_system.py
File “rpi_camera_surveillance_system.py”, line 65
frame = output.frame
^
IndentationError: unindent does not match any outer indentation level
Hi Harrie.
It seems that you have a syntax error when it comes to indentation.
You may have modified something when you copied the code.
Try creating a new file by copying the code from here: https://raw.githubusercontent.com/RuiSantosdotme/Random-Nerd-Tutorials/master/Projects/rpi_camera_surveillance_system.py
I hope this helps,
Regards,
Sara
Hi,
Got it working at once 🙂 just wondered if I can change from network cable to usb wifi dongel instead without making change in code?
Hi Frode.
Yes. It should work fine.
Regards,
Sara 🙂
Is it any way to change port to 80? When i change it in code i am getting an error:
” Traceback (most recent call last):
File “rpi_camera.py”, line 84, in
with picamera.PiCamera(resolution=’640×480′, framerate=24) as camera:
File “/usr/lib/python3/dist-packages/picamera/camera.py”, line 433, in __init__
self._init_preview()
File “/usr/lib/python3/dist-packages/picamera/camera.py”, line 513, in _init_preview
self, self._camera.outputs[self.CAMERA_PREVIEW_PORT])
File “/usr/lib/python3/dist-packages/picamera/renderers.py”, line 558, in __init__
self.renderer.inputs[0].connect(source).enable()
File “/usr/lib/python3/dist-packages/picamera/mmalobj.py”, line 2212, in enable
prefix=”Failed to enable connection”)
File “/usr/lib/python3/dist-packages/picamera/exc.py”, line 184, in mmal_check
raise PiCameraMMALError(status, prefix)
picamera.exc.PiCameraMMALError: Failed to enable connection: Out of resources “
Hi Stefano.
Accordingly to this discussion: github.com/waveform80/picamera/issues/488
It seems that your camera is already being used on the background.
You need to close the camera instance by using: camera.close()
Take a look at this link, I think this may be the solution:
raspberrypi.org/forums/viewtopic.php?t=155304
Then, to prevent this from happening again, I suggest adding the camera.close() at the end of the camera streaming script.
I hope this helps. Let me know if it solves your problem.
Regards,
Sara 🙂
Hi, it gives me an error at importing socketserver library, what shoul I do?
Hi Judit.
What error are you getting?
I’ve seen this problem before, check if you are using Python 2.x or Python 3.x the name of the library you are trying to import is different. The library in Python2 is SocketServer, while the library in Python3 is socketserver. By default, a raspberry pi running on Raspbian would use python 2.
SOLUTIONS:
1. when running the script, type python3 .py
2. change all instances of socketserver in the program to SocketServer
Hi, whenever I try to run your code through the Python 3 IDLE I get the response that the syntax is invalid. Here is exactly what is in my code:
Python 3.5.3 (default, Jan 19 2017, 14:11:04)
[GCC 6.3.0 20170124] on linux
Type “copyright”, “credits” or “license()” for more information.
>>> # Web streaming example
# Source code from the official PiCamera package
# http://picamera.readthedocs.io/en/latest/recipes2.html#web-streaming
import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server
PAGE=”””\
Raspberry Pi – Surveillance Camera
Raspberry Pi – Surveillance Camera
“””
class StreamingOutput(object):
def __init__(self):
self.frame = None
self.buffer = io.BytesIO()
self.condition = Condition()
def write(self, buf):
if buf.startswith(b’\xff\xd8′):
# New frame, copy the existing buffer’s content and notify all
# clients it’s available
self.buffer.truncate()
with self.condition:
self.frame = self.buffer.getvalue()
self.condition.notify_all()
self.buffer.seek(0)
return self.buffer.write(buf)
class StreamingHandler(server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == ‘/’:
self.send_response(301)
self.send_header(‘Location’, ‘/index.html’)
self.end_headers()
elif self.path == ‘/index.html’:
content = PAGE.encode(‘utf-8’)
self.send_response(200)
self.send_header(‘Content-Type’, ‘text/html’)
self.send_header(‘Content-Length’, len(content))
self.end_headers()
self.wfile.write(content)
elif self.path == ‘/stream.mjpg’:
self.send_response(200)
self.send_header(‘Age’, 0)
self.send_header(‘Cache-Control’, ‘no-cache, private’)
self.send_header(‘Pragma’, ‘no-cache’)
self.send_header(‘Content-Type’, ‘multipart/x-mixed-replace; boundary=FRAME’)
self.end_headers()
try:
while True:
with output.condition:
output.condition.wait()
frame = output.frame
self.wfile.write(b’–FRAME\r\n’)
self.send_header(‘Content-Type’, ‘image/jpeg’)
self.send_header(‘Content-Length’, len(frame))
self.end_headers()
self.wfile.write(frame)
self.wfile.write(b’\r\n’)
except Exception as e:
logging.warning(
‘Removed streaming client %s: %s’,
self.client_address, str(e))
else:
self.send_error(404)
self.end_headers()
class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
allow_reuse_address = True
daemon_threads = True
with picamera.PiCamera(resolution=’640×480′, framerate=24) as camera:
output = StreamingOutput()
#Uncomment the next line to change your Pi’s Camera rotation (in degrees)
#camera.rotation = 90
camera.start_recording(output, format=’mjpeg’)
try:
address = (”, 8000)
server = StreamingServer(address, StreamingHandler)
server.serve_forever()
finally:
camera.stop_recording()
Thanks
Hi.
What is the syntax error that you’re getting?
Regards,
Sara 🙂
I get an error object has no attribute condition
What I am doing when this error occurred
When does that error happen? Can you provide more details? Which Camera, Raspbian OS version, Python version are you using?
Hello
I got the camera working good, but the day after the camera is not available. I have to run python3 rpi_camera_surveillance_system.py through putty to get it going again. Is it possible to get it to run 24/7?
Hello I am going to try this solution since I want to use to raspberris one for live transmission and other for whatching it …… However I don-t have the raspi cam any suggestion about using a usb web cam?? I can already read the webcam using openCV4 but what change should I do in this code to read that cam instead of raspi cam? Thanks
Hi Lennon.
If you want to use two raspberry pi boards one for transmission and the other for you to watch, I suggest using MotionEye OS.
It usually supports USB cameras.
I recommend taking a look at the following tutorials and see if it helps:
– https://randomnerdtutorials.com/install-motioneyeos-on-raspberry-pi-surveillance-camera-system/
– https://randomnerdtutorials.com/cctv-raspberry-pi-based-system-storage-motioneyeos/
– https://github.com/ccrisan/motioneye/wiki
Regards,
Sara 🙂
i try it but if i want shoot a photo when object move around a pir the camerapi ontrol in nodered not respond the problem is a pyton that take complete control of cam
but for me is interesting take a photo with a person move around my pir
any idea?
Hi Fabio.
You can use motioneyeOS that allows you to install a complete CCTV system with lots of functionalities.
It has the option of taking a photo when motion is detected. If you want to record and take photos when motion is detected, I think motioneye is one of the best options – to install and to use.
Here are two tutorials about motioneye that you can easily replicate and adapt to your project:
– https://randomnerdtutorials.com/install-motioneyeos-on-raspberry-pi-surveillance-camera-system/
– https://randomnerdtutorials.com/cctv-raspberry-pi-based-system-storage-motioneyeos/
Regards,
Sara
Nice script, works great. Has anyone tried H.264 as a stream? My camera is capable of it but I have not tried it yet. I was just going to change output from mjpeg to h264. Thanks for your time.
Hi Joe.
I haven’t tried that, but I think it is possible. You have to try it.
Regards,
Sara
Fantastic!
This is amazing for a dinosaur like me to get into. I really need to get into more Python coding though, and to think everything was done in assembly code a long time ago. Things have changed so much.
Well done!!
Thanks 🙂
Thanks John.
We’re glad you enjoyed the example.
Regards,
Sara 🙂
hello can you help me, Im getting an error
mmal: mmal_vc_port_enable: failed to enable port vc.null_sink:in:0(OPQV): ENOSPC
mmal: mmal_port_enable: failed to enable connected port (vc.null_sink:in:0(OPQV))0x1a6f8d0 (ENOSPC)
mmal: mmal_connection_enable: output port couldn’t be enabled
Traceback (most recent call last):
File “rpi_camera_surveillance_system.py”, line 84, in
with picamera.PiCamera(resolution=’640×480′, framerate=24) as camera:
File “/usr/lib/python3/dist-packages/picamera/camera.py”, line 433, in __init__
self._init_preview()
File “/usr/lib/python3/dist-packages/picamera/camera.py”, line 513, in _init_preview
self, self._camera.outputs[self.CAMERA_PREVIEW_PORT])
File “/usr/lib/python3/dist-packages/picamera/renderers.py”, line 558, in __init__
self.renderer.inputs[0].connect(source).enable()
File “/usr/lib/python3/dist-packages/picamera/mmalobj.py”, line 2212, in enable
prefix=”Failed to enable connection”)
File “/usr/lib/python3/dist-packages/picamera/exc.py”, line 184, in mmal_check
raise PiCameraMMALError(status, prefix)
picamera.exc.PiCameraMMALError: Failed to enable connection: Out of resources
Hi Rey.
Accordingly to this discussion: github.com/waveform80/picamera/issues/488
It seems that your camera is already being used on the background.
You need to close the camera instance by using: camera.close()
Take a look at this link, I think this may be the solution:
raspberrypi.org/forums/viewtopic.php?t=155304
Then, to prevent this from happening again, I suggest adding the camera.close() at the end of the camera streaming script.
I hope this helps.
Regards,
Sara 🙂
great tutorial
any way to adjust the exposure?
Hi.
For adjusting the exposure using the picamera library, take a look at the following documentation:
– picamera.readthedocs.io/en/release-1.10/api_camera.html#picamera.camera.PiCamera.exposure_mode
– picamera.readthedocs.io/en/release-1.13/recipes1.html#capturing-consistent-images
Regards,
Sara
Thank you for the great tutorial
i also want to ask “how can i display sensor data(ex . temperature) along side the camera feed?” . i am still new to python programming dont know much about the libraries used in program .
Hi.
Thank you for following our tutorials.
Unfortunately, we don’t have information about what you’re looking for.
I think the information on the following link is a good starting point
raspberrypi.org/forums/viewtopic.php?t=35487
I hope this helps.
Regards,
Sara
Hi
Thank you so much for this, it works very well
Thanks Alot you made my day 😀
You’re welcome.
Regards,
Sara
First of all I would like to thank you for giving such a helpful content. I wanted to add led light (powered by the raspberry pi) in front of the pi camera, but I do not know how to turn on and off using the webpage. I need help to control the led from the same page (streaming webpage) by adding some buttons.
thank you in advance.
Hi.
We have a tutorial about controlling an LED via web server with the Raspberyr Pi. You may found it useful for your project.
https://randomnerdtutorials.com/raspberry-pi-web-server-using-flask-to-control-gpios/
Regards,
Sara
hi, it worked very well in the first attempt, after trying for hours with other codes.
thank you. but, can u help me with how the code works?
Hi Tharun.
Thank you for your interest, but we we don’t have any code explanation for this specific project.
Regards,
Sara
hey.. i want a code which can perform video streaming meanwhile save the videos of previous days i.e; the picamera has to save the videos daily while its streaming…..
Hi.
The best way to do that is using MotionEyeOS.
You can check our tutorials about MotionEyeOS below:
https://randomnerdtutorials.com/install-motioneyeos-on-raspberry-pi-surveillance-camera-system/
https://randomnerdtutorials.com/cctv-raspberry-pi-based-system-storage-motioneyeos/
I hope this helps.
Regards,
Sara
Worked like a charm !!
The only change I had to make was on this line:
# removing the parameters.
with picamera.Camera() as camera:
Thank you for the excellent tutorial !
Hi Rui/Sara
Great tutorial as many others, i dabble about with raspberry pi’s alot, but i am not very techie or coder.
I installed your rpi_camera_surveillance_system.py and is working great, but my question is can i add to the script to have email notification with a picture as if a button was pressed like a doorbell.
I have tried motion and motioneye but did not get on with them.
Regards
Tony
Hi Tony.
motioneye is probably the best solution for what you are looking for, and it is very easy to use.
You can set up all your cameras in a graphical interface and send notifications when motion is detected. You can follow our tutorials about motionEye and see if you can follow through:
– https://randomnerdtutorials.com/install-motioneyeos-on-raspberry-pi-surveillance-camera-system/
– https://randomnerdtutorials.com/cctv-raspberry-pi-based-system-storage-motioneyeos/
We don’t show motion detection or email notification in our tutorials, but you can easily search that online and see the settings you need to fill. Also, explore the user interface, and you’ll be able to find how to do that.
Regards,
Sara
Awesome work!
Hi,
In case anybody needs this. Here is the answer to my question.
import SocketServer
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class StreamingServer(SocketServer.ThreadingMixIn, HTTPServer):
Thanks Jerry
Great toturial!
I was able to get it working through the browser but is there a way to get to work on a vlc media player? I have had no luck with it so far.
Hi Mike.
We don’t have any tutorial about that subject.
Regards,
Sara
what if i use the logitech webcam ? did we use the same source code?
what if i use the logitech webcam ? did we use the same source code?
and can you show me the source code?
thank you..
Hi.
I think this code only works with the Raspberry Pi Camera.
If you want to use other cameras like webcams, the easiest way is to use motioneyeOS https://randomnerdtutorials.com/install-motioneyeos-on-raspberry-pi-surveillance-camera-system/
There should be other codes compatible with USB cameras, but I don’t have any example about that at the moment.
Regards,
Sara
Man, I love it when a project is just
1. Copy
2. Paste
Great work, thanks very much!
Actually, just one question: how do I flip the camera view? I’ve had to mount mine upside down because of the camera holder.
Never mind, got it. Pro tip: read the comments in the code!
Thanks again!
Thank you for following our work 😀
worked straight out of the box.
Thankx
Great!
Hi, can we browse video stream of pi camera on android app ?
Hi.
It should be possible, but we don’t have any project about that subject.
Regards,
Sara
Hi, Folks,
Good Job! It’s not the first time I’m cross with yours works and here I am question again.
All I know about PI, which it’s not too much, I learned of my own. I would like to know if I can use this project in a different manner.
Is there any way of camera shows up in your device just only when I press a button in GPIO for example? I’m trying to do a door entry intercom Video/audio. Any clue?
Just like to say thanks, works really well.
Thanks 😀
I had trouble using this but after some struggle I figured it out (I’m new to Python):
Error I was getting:
pi@raspberrypi ~ $ python3 rpi_camera_surveillance_system.py
Traceback (most recent call last):
File “rpi_camera_surveillance_system.py”, line 80, in
with picamera.PiCamera(resolution=’640 480′, framerate=24) as camera:
File “/usr/lib/python3/dist-packages/picamera/camera.py”, line 488, in __init__
self.STEREO_MODES[stereo_mode], stereo_decimate)
File “/usr/lib/python3/dist-packages/picamera/camera.py”, line 561, in _init_camera
w, h = resolution
ValueError: too many values to unpack (expected 2)
So in rpi_camera_surveillance_system.py above line 81 I added:
tupl = (640,480)
and then changed line 81 to call the tupl instead
with picamera.PiCamera(resolution=tup1, framerate=24) as camera:
and that solved my problem.
I hope this helps somebody.
Thanks for sharing.
Regards,
Sara
Yes, this information very well. thank you
Great tutorial – after having tried for a whole day, I stumbled over this explanation and got it working within 10 mins. Thanks!
in these project i don´t have to use open cv right?
Right.
Regards,
Sara
No, you don’t have to use OpenCV. It’s just a Python script running
why when i run the program for live feed there is no picture on the page?
here is error from terminal: 192.168.1.140 – – [03/Jan/2020 15:43:07] “GET /index.html HTTP/1.1” 200 –
192.168.1.140 – – [03/Jan/2020 15:43:07] “GET /stream.mjpg HTTP/1.1” 200 –
WARNING:root:Removed streaming client (‘192.168.1.140’, 52140): [Errno 104] Connection reset by peer
can you reply me i want to fix this error.
Thank you~ I run the script in my Raspberry pi successful ^-^
pretty wonderful tutorial~
thank you very much~
support yours always
Hi
can it stream both audio and video
Hi.
This particular example streams video only. We don’t have any example about audio.
Regards,
Sara
Great Tutorial. I have a question. I would like to have the Pi Zero W take a Pic and up load to a cloud service(Adafruitio) then shutdown properly. I could use an ESP8266 to wake the Pi with a relay. Is there a way to have the Pi boot run a program then shut down and poweroff. Thanks
Ramey
Hello! Great project! It works perfectly with just copy and paste, thank you.
I use my camera in a dark place, so I need to switch on the light with a relay connected to a raspberry port.
I do it with command line…could you be so gentle to add a button under the image to command a GPIO on and off please? Sorry but I’m not able to do it.
Thank you.
Can audio be streamed with the video?
Hi.
This example doesn’t stream audio.
Regards,
Sara
Hi Sara,
Great tutorial.
I am using a ‘PI zero w’ and it works great.
My next step it to implement tilt/pan.
Thanks
Hans
That’s great!
Regards,
Sara
I just came across this and I was happy to get it running out of the box so to speak. An excellent bit of code.
I found that Chrome in it’s latest incarnation is a poor web client though, it kept freezing after a while. The latest firefox is fine.
Great stuff.
70 yr old noobie youngster. did everything required but when I ran the start command I got the following:Traceback (most recent call last):
File “rpi_camera_surveillance_system.py”, line 2, in
import picamera
ModuleNotFoundError: No module named ‘picamera’
As I am using a wave share OV5647 and not the pi camera V2, (one arriving tomorrow) that is obviously the problem. I suspect that I need to change that line to read something along the lines of “import OV5647” but I don’t know the actual modules computer name. Or am I barking up the wrong tree
Hi Mike.
This particular project only works with the PiCamera.
When using the picamera make sure you have enabled the camera on the Raspberry Pi settings.
Regards,
Sara
Well, I’ve got the Pi Camera (v2), mounted the pi and the camera in the nice red and white case that I bough only to find that the case wall is too thick to allow the mini HDMI male to mate properly with the female. So after some surgery with the craft knife it’s now up and running……….except for: python3 rpi_camera_surveillance_system.py
Traceback (most recent call last):
File “rpi_camera_surveillance_system.py”, line 2, in
import picamera
ModuleNotFoundError: No module named ‘picamera’
Fortunately I have a fair bit of hair left to pull out in frustration while waiting a reply to say that the software only works with V1 (?)
Hi again.
I was using V2 camera.
Can you run this on the terminal?
sudo apt-get install python3-picamera
Hi Sara,
I have no problem using picamera, but is there a way to use usb camera?
The USB camera is Logitech c270.
Hi.
This particular project, only works with the PiCamera.
You can use motioneyeos to add all sorts of cameras: https://randomnerdtutorials.com/install-motioneyeos-on-raspberry-pi-surveillance-camera-system/
https://randomnerdtutorials.com/cctv-raspberry-pi-based-system-storage-motioneyeos/
Regards,
Sara
Thank you very much this works almost perfect. I used it for the camera live feed on octopi. There was a little issue i could solve already. octopi adds a random paramter to the end.
So the request was “http://:8000/stream.mjpg?13541253” which could not be interpretet and caused a 404 answer
by splitting the string with
noParam = self.path.split(“?”,1)[0]
and using — noParam == “/stream.mjpeg” — instead of — self.path == “/stream.mjpg” —
i could solve the problem
What i love about this is the low CPU usage of aprox 7% on my raspberryPi 3B+ and the low latency way smaller the 1 second
OMG after days of trying dinosaur old things I found on the web I stumbled across this and it works!!! All I had to do was use your reply to Mike Wilson “sudo apt-get install python3-picamera” to swat the same error he was getting and I’m a happy camper. Thank you so much and stay safe in these weird times!
-Rob
Great tutorial! Thanks for that! It works pretty good for me.
One thing is missing for me. I want to increase the resolution to 1080p (1920 x 1080). When I changed parameters from 640×480 in two places, it seems like i’m getting a cropped image. Any ideas on how to get higher res stream?
Thanks again!
A bit late and maybe you figured it out by yourself now but here is what i’ve done :
at the top of the script change this :
To the width and height you want your video to be shown on the browser in your case you should have :
Is it just me or did the part that you put after the colons your comment not show up? On my end it looks like this:
“A bit late and maybe you figured it out by yourself now but here is what i’ve done :
at the top of the script change this :
To the width and height you want your video to be shown on the browser in your case you should have : ”
Where there’s nothing after the colons.
Could you try typing it again? Thanks!!
Thanks that was a great tutorial worked perfectly and was exactly what I have been looking for _/_
Great! 🙂
Thanks for that, I’m using it on a pi buggy that wanders around the house, (when the cat lets it). I had to dial back the fps to 2 to stop stressing the first generation pi I’m running it on, but works a treat now.
Excellent job with the script. Worked like a charm on first try!
Hello,
First of all, thanks for this post!
You say the camera can be accessed by any device on the local wi-fi.
While in my case it works for the browser running on the RPi, none of my other devices could access the camera using the local IP address.
I have searched the ‘net, but found nothing relevant.
Any suggestions?
BTW, Feliz Ano Novo !
Hi Sara –
After playing around with both MotionEyeOS and MotionEye running on a Raspberry pi 3 I was delighted to finally find something to stream video with almost no latency. Excellent! And your script worked out of the box. The video shows up on any machine’s browser in my network. All I tried before had latencies of up to 10 seconds which rendered a surveillance camera almost useless.
However, I wanted to stream the video from the Raspi (as a network camera) to MotionEye on a PC operated by Ubuntu Linux. But MotionEye refuses to add the camera saying “not a supported network camera”. The camera was specified as “Simple MJPEG camera”. Do you have an idea what I can do?
Regards from Hamburg
Rudi
Hi Rudi.
I’m glad the project worked straight out of the box.
As for the motioneyeOS issue, I have no idea.
I recommend posting an issue in the motioneyeos forum.
Regards,
Sara
Hi, thanks for your great job. I tested it and the framerate is really good. Also, I tested the same way with Flask (Miguel Grinberg’s job) but the framerate is bad.
You use mpeg streaming but with Flask it’s alway jpeg frames and I guess this occur latency.
My question is : is it possible to use websocket with your streaming’s example? I would like add button and data to the web page where there is the streaming.
Regards,
Steph
Hi Sara,
How can I stream an objects’ detection video? At the moment I can only see this through the HDMI output of the Raspberry pi.
Could you help? I can supply the code for a better reference.
Thanks!!!
Thank you so much!! Worked like a charm 🙂
Hi first of all thank you for the articel. I am using my pi camera with a jetson nano dev. board. Does this script works with jetson too or should I make changes in the script? If it doesn’t work which changes should I apply? I would be glad if you answer.
Hello, help. I am trying to use openCV to take the streamed video footage and apply image processing code. I am starting simple with trying to convert the video to grayscale. I am unsure of what needs to change in the original code in order to get it to work well with openCV library, any advice on where to start? The end goal will be for the code to stream video that identifies shapes within the frame. Thanks!
Great project and super code! I have the Pi camera and it worked fine. But not I need to go to a USB Connected camera for a new project. Any chance you have similar python code for using a USB (Logitech) connected camera instead. I can’t change O/S to the MotionEyeOS because the Pi that needs to run this is a special with Zwave, and THUM Sensor code system that has been running for more than 3 years. I do truly like your web server feature, so I am hopeful there is Python code changes that you can suggest to move from a Pi Camera to the USB Camera. I’m new to Python, so the learning curve would be steep for a 70+ year old to master in a reasonable time. Thanks for your help.
Check this out and let us know if it did work for you
hada-tech.com/index.php/2020/06/07/live-stream-usb-camera-with-raspberry-pi/
Already did that a couple of years ago. I like the simplicity of the Python code solution here, just inquiring if they had a similar Python code for a USB camera instead of the Pi Camera. I’ll keep looking. Thanks for your input.
Hello,
This tutorial is fantastic, thank you so much! I am however having an issue when trying to make a simple modification of this code that I was hoping someone would be able to help with. I have been able to get the code to work perfectly as is, but now I need to change the port from port 8000 to port 80. I thought this would be a simple switch of just changing out the line that says
address = (”, 8000)
to instead be
address = (”, 80)
but this gives me the following errors:
Traceback (most recent call last):
File “rpi_camera_surveillance_system2.py”, line 92, in
server = StreamingServer(address, StreamingHandler)
File “/usr/lib/python3.7/socketserver.py”, line 452, in init
self.server_bind()
File “/usr/lib/python3.7/http/server.py”, line 137, in server_bind
socketserver.TCPServer.server_bind(self)
File “/usr/lib/python3.7/socketserver.py”, line 466, in server_bind
self.socket.bind(self.server_address)
PermissionError: [Errno 13] Permission denied
I have made sure to keep the conditions exactly the same when running the original versus edited code, but it has not made a difference. Any help would be very appreciated!
Thanks,
Kerri
Reminder, the PiOS is just a linux kernel. To use ports <1024, you must run your code as root.
It’s been two weeks of web search to find a solution to stream my picam on my computer/phone/TV browser.
I found a lot of things and none of them was working the way i wanted until now.
Thanks a lot for this one, and the html code in your script is just a perfect thing that allows some customization.
LOVED IT
Hello,
Thank you so much for tutorial! Is there a way to make the script run after boot? So all that’s needed is to turn on the Pi and the stream becomes available?
Thanks!
Hi Ben.
I think this article explore exactly what you are looking for: raspberrytips.com/autostart-a-program-on-boot/
Regards,
Sara
Sara, I absolutely love the fact that you take the time to respond to all these issues. Very impressive. Good for you.
Hi.
Thanks for noticing that.
I try it. But in fact, I can’t answer all the comments or solve all the problems. But I try to help as much as I can.
Regards,
Sara
Hello there. Thank you very much for your hard work.
I’m new in this world. I was able to make it run, perfectly. I’d thank you for it.
But, actually I would like to be able to access from a different network, it would be possible without using MotionEyeOS?
I added a few sensors, and I would like to used it on my car and access using mobile internet.
Do you have any tip for me?!
Thank you very much once again.
Kind regards
Hi.
You can consider using ngrok: https://ngrok.com/
Regards,
Sara
I’ll take a look.
Thank you, Sara.
Kind regards.
It is working perfectly, thank you. Would like to know if it is possible to store the videos in the computer through the local IP address? And can object detection alogrithm be used on a computer from the live streams using the IP address?
Hi, we are just wondering where ‘output’ is defined in the StreamingHandler class as we cannot see it. When trying to run this inside another thread we get an ‘output’ not being defined, but it does not seem to be being defined in your code either? Thanks.
In python, your scope is inclusive. This means that the output variable created in the with picamera.PiCamera(…) as camera: section, it is included in the scope when calling StreamingHandler during the streaming server declaration.
Hello Sara,
If only I had found your solution first, I would have saved a lot of time !!! The great thing is that it all worked out the first time and without too many complicated code! Strong and simple !
A big thank you to you !
Kind regards.
Hack
Hello,
Is there anyway to pause the script, while kodi is running?
Thanks
Joao
I would like to take a still picture in the form of a jpeg. I was wondering what code I would need to include to the already existing one.
I have been looking far and wide to update the video image with the current date/timestamp. I found an obscure piece of code: switchdoc.com/2019/07/mjpeg-mjpg-python-streaming-overlay/.
After fixing this code to work with the current version of python, i was able to get a timestamp working. However this extra processing causes the framerate to dip to less than 10 frames a second (i’d guess its less than 5, but i didn’t actually count). There is a method already included in picamera.PiCamera called annotate_text. What is the best method to either call this method once a second? or some other method to update the image?
Thanks.
I had a question regarding the IP address. Is there anyway to get around the issue of the RPi’s IP address changing? It happens every so often, causing me to have to go back into the RPi to find the new one so I can go to its new streaming URL. It’s particularly pesky because I have this IP-dependent URL embedded in code elsewhere, meaning that I need to update the code with each new IP address.
Thank you for any insight you can provide.
Hi.
We don’t have any tutorials about that.
But I found this article that should be what you’re looking for: https://www.makeuseof.com/raspberry-pi-set-static-ip/
Regards,
Sara
Hi, have the problem on my esp32 cam I thinker concerning the driver when running the program in my computer, which driver support to be used
Hi Anne,
You can set a Static (fix) IP address in the tab “Networking”.
Login as admin
Klick on the most left button and lookup the tab “networking”
Change dynamic into static. Make sure you stay in the range of your IP addresses but a little out of the most used ones. I have set for example 192.168.1.230, but for you it can be something else of course.
Have fun
A great project! Thanks! I wonder, could it be possible to set the exposure time say, to a max of 3 seconds and a minimum of 1s…? I am trying to use it in a place that is poorly illuminated.
Hi there! Great project!
I just wanted to know if it’s possible to change the streaming quality, because I think it’s not the utmost camera quality.
Hi, thankyou so much for this solution. Really helped with my final year project. I just wanted to know how I can combine a code for a motion sensor into this code.
I installed v4l2rtspserver, and played the rtsp stream with ffplay, and it works, but there’s a video delay. Then there’s the problem of serving an rtsp stream in a web page.
This is very simple, and there’s practically no delay! Thank you!
I got it to work on a Raspberry Pi Zero while it was connected to a monitor but when I tried to
SSH the command… python3 rpi_camera_surveillance_system.py
It returned an error message saying camera not connected? So I did sudo raspi-config and made sure it was enabled and it gave me the same error message?
It is strange because it works fine when I put that command into the terminal from the monitor attached top the Pi?
disregard my question….I reformatted a new card and everything worked LOL
Thanks for a great tutorial
Hello, getting this error on my raspberry pi4b. Please help.
OSError: libmmal.so: cannot open shared object file: No such file or directory
Hi,
Can you suggest the modification in the code such that it can also be transmitted to a device that is not connected to the same network as raspberry pi
Hi.
You can use a service like ngrok or Cloud Flare Zero trust for example.
Regards,
Sara
Working fine with Raspi 4 and Camera Module v2.1
Wasn’t expecting that there is only a slight delay less than 100ms.
Awesome simple script. Much thanks!
Forgot to mention that I used a stream at 720p30
Thank you, it work well in couple of time, after about 10 min. i have this message “WARNING:root:Removed streaming client (‘192.168.2.121’, 50426): [Errno 104] Connection reset by peer” after i loose the connection, i use Raspberry Pi B+
Thank you if someone have the solution.
Thank you so much for post.
Could you elaborate on ffmpeg ports used for output stream:
I have rtmp server running on a cloud (say eg. 11.23.123.13 in port 1935 for rtmp & 4936 for rtmps). However is there any port on sending end , i should request team to open to avoid blocking the stream sending from device end to rtmp server end(camera streaming end). Only port 443 is open in device where camera connected and ffmpeg commands are running.
It would be helpful if somebody give insights on how network is connecting from ffmpeg encoder to rtmp server
Getting the details how network is connecting from ffmpeg encoder to rtmp server?
Which ports to be open in device end(where camera connecting) to start ffmpeg streaming to rtmp server running on cloud?
Potential to have this updated for picamera2? The new pi cameras seem to require it? The ability to change the python script to work is beyond my capabilities.
Hi.
Thanks for the suggestion.
Unfortunately, at the moment, I don’t have a picamera 2 to experiment with.
Regards,
Sara
There are lot’s of exaples here: https://github.com/raspberrypi/picamera2
I also stumbled on this issue when using the latest Raspian OS (BullsEye) where only Picamera2 is installed.
Hello,
I’m having problems with the code.
~$python3 rpi_camera_surveillance_system.py
Traceback (most recent call last):
File ‘rpi_camera_surveillance_system.py’, line 6, in
import picamera
ModuleNotFoundError: No module named ‘picamera’
~ $
Paspbery Pi 3B+
OS: Raspberry Pi Lite (Buster)
Raspberry Pi Camera Rev 1.3
I would be very grateful for your help.
Greetings from Bavaria
horst
Hi.
Check this suggestion: techoverflow.net/2019/11/21/how-to-fix-modulenotfounderror-no-module-named-picamera/
Regards,
Sara
Hi Sara,
it worked! The camera is now working properly. Thanks a lot for your help.
greeting
horst
That’s great.
I’m glad everything is working as expected now.
Regards.
Sara
P.S. Visited Bavaria last year and this year again. We loved it.
Hello,
Thank you for the information. Is there a way to have a camera connected to a Raspberry Pi and stream video but also be an access point and not connect to an existing wireless network, similar to one of the ESP32-camera projects?
Thanks in advance
Phil
Hello,
Great tutorial! It runs successfully on my Raspbian Buster install. I have another Pi running Debian Bookworm. However, since the raspicam package is now deprecated, the script no longer works. Can anyone suggest a tutorial to stream camera video via libcamera with Python? TIA for any suggestions.
Hi Steve,
take a look at this: https://github.com/raspberrypi/picamera2/blob/main/examples/mjpeg_server.py
This script use picamera2 with libcamera.
Otto
Hi Otto,
Thanks for the link. The scripts works in Rasbian Bookworm. The only problem I have now is how to add lines that will flip the stream horizontally and vertically. Adding “Picamera2.vflip = True” after the “from picamera2 import Picamera2” entry doesn’t change the orientation.
Check out these examples:
pypi.org/project/picamera2/0.2.2/
Rotate all the images by 180 degrees.
config = picam2.preview_configuration(transform=libcamera.Transform(hflip=1, vflip=1))
picam2.configure(config)
Otto
I don’t know where to add those lines to the script or if any other lines need to be commented out. I tried adding the lines to the script right after the picam = Picamera2() line but the the stream is still showing upside down. Thanks.
hello , when i copied the script and tried to run it it showed
Traceback (most recent call last):
File “/home/pi/rpi.py”, line 6, in
import picamera
ModuleNotFoundError: No module named ‘picamera’
please tell me what to do in these situation
Hi Sara,
Thank you for the post. I was able to get it to work on a pi micro on a rc excavator I have, Thank you for the inspiration. I learned alot about streaming through your article.
I am trying to get a front view and bucket view if that makes sense. I have read about how to get a second camera but the python part i am not familiar with. Do you have any ideas or direction on the idea to have two camera feeds on the steaming page?
Thank you again for the post. I really enjoyed it!!
Mike E
it worked for me. Now I just need to figure out how to stream to ARDUpilot, or Qgroundcountrol, from my drone.
Awesome, tried 5 different things, this is the only thing that worked for me
hello,
i am using the legacy bullseye 64 bit version OS for my raspberry pi 4.
When i run the script i get this error:
Traceback (most recent call last):
File "/home/anas/CameraVideoStream.py", line 8, in <module>
import picamera
File "/usr/lib/python3/dist-packages/picamera/__init__.py", line 72, in <module>
from picamera.exc import (
File "/usr/lib/python3/dist-packages/picamera/exc.py", line 41, in <module>
import picamera.mmal as mmal
File "/usr/lib/python3/dist-packages/picamera/mmal.py", line 49, in <module>
_lib = ct.CDLL('libmmal.so')
File "/usr/lib/python3.9/ctypes/__init__.py", line 374, in __init__
self._handle = _dlopen(self._name, mode)
OSError: libmmal.so: cannot open shared object file: No such file or directory
I seem to get this error even for other examples but i can’t figure out the fix i would appreciate it if anyone can help out.
same, found any solution yet?
Maybe it’s better to check our newest tutorials
https://randomnerdtutorials.com/raspberry-pi-picamera2-python/
https://randomnerdtutorials.com/raspberry-pi-mjpeg-streaming-web-server-picamera2/
I hope this helps.
Regards,
Sara
You probably know well, but it does not work with newest 64-bit OS from Raspberry.
Took an hour to find out, but no easy solution either.
Hi.
You can try this tutorial instead: https://randomnerdtutorials.com/raspberry-pi-mjpeg-streaming-web-server-picamera2/
Regards,
Sara
Hello,
The camera works on port 8000
http://ipaddress:8000/index.html
How do I embed this into another webpage ?
I’ve tried
Your browser does not support the video ag.
and it says unsupported MIME type