Video Streaming with Raspberry Pi Camera

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:

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()

View raw code

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.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

197 thoughts on “Video Streaming with Raspberry Pi Camera”

      • 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!!!

        Reply
  1. Excellent article guiding the new builder . I successfully built the project at one attempt and monitoring my house.
    Thank you

    Reply
  2. 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!!!!

    Reply
  3. 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

    Reply
    • 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.

      Reply
  4. 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?

    Reply
  5. 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?

    Reply
  6. 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 ?

    Reply
  7. 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!!!

    Reply
  8. 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.

    Reply
  9. 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

    Reply
    • 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 🙂

      Reply
    • 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 🙂

      Reply
    • 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 🙂

      Reply
  10. 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

    Reply
  11. 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?

    Reply
  12. 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 “

    Reply
    • 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 🙂

      Reply
    • 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

      Reply
  13. 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

    Reply
  14. 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?

    Reply
  15. 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

    Reply
  16. 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?

    Reply
  17. 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.

    Reply
  18. 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!!

    Reply
  19. 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

    Reply
    • 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 🙂

      Reply
    • 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

      Reply
  20. 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 .

    Reply
    • 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

      Reply
  21. 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.

    Reply
  22. 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?

    Reply
    • Hi Tharun.
      Thank you for your interest, but we we don’t have any code explanation for this specific project.
      Regards,
      Sara

      Reply
  23. 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…..

    Reply
  24. 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 !

    Reply
  25. 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

    Reply
  26. 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

    Reply
  27. 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.

    Reply
  28. 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?

    Reply
  29. 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.

    Reply
  30. Great tutorial – after having tried for a whole day, I stumbled over this explanation and got it working within 10 mins. Thanks!

    Reply
  31. 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

    Reply
  32. Thank you~ I run the script in my Raspberry pi successful ^-^
    pretty wonderful tutorial~
    thank you very much~
    support yours always

    Reply
  33. 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

    Reply
  34. 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.

    Reply
  35. 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

    Reply
  36. 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.

    Reply
  37. 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

    Reply
    • 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

      Reply
      • 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 (?)

        Reply
  38. 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

    Reply
  39. 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

    Reply
  40. 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!

    Reply
    • 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 :

      Reply
      • 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!!

        Reply
  41. 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.

    Reply
  42. 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 !

    Reply
  43. 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

    Reply
    • 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

      Reply
  44. 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

    Reply
  45. 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!!!

    Reply
  46. 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.

    Reply
  47. 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!

    Reply
  48. 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.

    Reply
  49. 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/

    Reply
    • 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.

      Reply
  50. 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

    Reply
  51. 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

    Reply
  52. 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!

    Reply
    • Hi Ben.
      I think this article explore exactly what you are looking for: raspberrytips.com/autostart-a-program-on-boot/
      Regards,
      Sara

      Reply
    • 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

      Reply
  53. 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

    Reply
  54. 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?

    Reply
  55. 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.

    Reply
    • 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.

      Reply
  56. 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

    Reply
  57. 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.

    Reply
  58. 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.

    Reply
      • 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

        Reply
    • 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

      Reply
  59. 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.

    Reply
  60. 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.

    Reply
  61. 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.

    Reply
  62. 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!

    Reply
  63. 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?

    Reply
  64. Hello, getting this error on my raspberry pi4b. Please help.

    OSError: libmmal.so: cannot open shared object file: No such file or directory

    Reply
  65. 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

    Reply
  66. 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!

    Reply
  67. 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.

    Reply
  68. 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?

    Reply
  69. 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.

    Reply
  70. 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

    Reply
    • Hi.
      Check this suggestion: techoverflow.net/2019/11/21/how-to-fix-modulenotfounderror-no-module-named-picamera/
      Regards,
      Sara

      Reply
        • 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.

          Reply
  71. 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

    Reply
  72. 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.

    Reply
      • 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.

        Reply
        • 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

          Reply
          • 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.

  73. 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

    Reply
    • 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

      Reply
  74. 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.

    Reply
  75. 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.

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.