Raspberry pi stream camera: How To Stream Live Video From Your Raspberry Pi Camera

How To Stream Live Video From Your Raspberry Pi Camera

When you purchase through links on our site, we may earn an affiliate commission. Here’s how it works.

(Image credit: Tom’s Hardware)

The official Raspberry Pi camera comes in many forms. From the original v1.3 all the way to the latest Raspberry Pi HQ camera, all use the same software. Using the raspistill and raspivid commands we can take still images and videos right from the terminal.

More advanced uses included manually controlling the white balance, color, saturation and brightness of an image and video. We can also create a simple video streaming service with just one line of code.

In this tutorial we will learn how to set up the camera, take a few test pics and then create a test stream to ensure that everything works before we launch into a project which creates video art using live video image effects that we can record on our desktop computer with very little effort.

Setting up a Raspberry Pi Camera 

If you’re already familiar with how to set up a Pi camera module, you can skip ahead. These steps will work for all Raspberry Pi camera modules (including third-party ones). 

With the Raspberry Pi powered off. 

1. Open the camera port by gently lifting the plastic lock upwards. 

(Image credit: Tom’s Hardware)

2. Insert the ribbon connector with the blue tab facing the USB / Ethernet ports. 

(Image credit: Tom’s Hardware)

3. Close the lock on the connector and give it a very gentle pull to make sure it is in place.

4. Power up your Raspberry Pi and then go to Preferences >> Raspberry Pi Configuration. 

(Image credit: Tom’s Hardware)

5. Click on the Enable button for the Camera found in the Interfaces tab.

(Image credit: Tom’s Hardware)

6. Click Ok and reboot the Pi.

7. Open a Terminal and type the following command to take a quick picture to test the camera. 

$ raspistill -o test.jpg

After five seconds has elapsed, an image will be taken and saved as test.jpg. Using the file manager check that the image is correct before moving on.

Testing a Stream 

To start a stream we need to open a terminal and enter a rather long command. Ensure that your Raspberry Pi is connected to the network. For the best performance use an Ethernet cable, Wi-Fi will work, but you may see dropouts.

1. Get the hostname of your Raspberry Pi. Open a terminal and type in this command for your hostname. Make a note of the hostname. You may need to add “.local” to the end, depending on your network. 

$ hostname

2. Run the streaming command. The one line command to run a video stream live from the camera is rather long, so let’s go through the command before we run it.

-o is our output, in this case set to none.

-t is the length of the video clip, using zero will set this to infinite.

-w and -h are the width and height of the video, in this case 800 x 600.

-fps are the frames per second for the video stream, a lower value should minimize dropouts.

| cvlc is a pipe which takes the output from the raspivid command, our video stream and streams the video using an h364 codec via real time streaming protocol (rtsp) over our network.

Run this command in a terminal on your Raspberry Pi.

raspivid -o - -t 0 -w 800 -h 600 -fps 12  | cvlc -vvv stream:///dev/stdin --sout '#rtp{sdp=rtsp://:8080/}' :demux=h364

3. On your Windows / Mac / Linux computer install VLC and then open VLC.

4. Go to Media >> Open Network Stream, or press CTRL + N.

(Image credit: Tom’s Hardware)

5. Enter the rtsp address and port of your Raspberry Pi. The rtsp address is your Raspberry Pi’s hostname, prefixed with rtsp://, and the port was set to 8080. Click Play to start the stream. Here is our example rtsp address.

rtsp://raspberrypi:8080/

(Image credit: Tom’s Hardware)

It will take VLC a few seconds to catch up with the stream, be patient. Soon you will see video streamed from your Raspberry Pi, with a delay of around 5 to 10 seconds.

6. To record a stream, click on Playback >> Record and then specify a filename. The recording will end when the stop button is pressed.

(Image credit: Tom’s Hardware)

Getting Arty: Streaming With Filters 

The final part of this project is where we get creative. We will be creating a script that will first create an array (a list) of all the possible image effects. Then we create a variable to store the length of the array, before randomly choosing a number in the array that will control which effect is used when our stream goes live. We shall be writing the code on the Raspberry Pi using a GUI text editor.

1. Launch Geany (from the menu) and create a new file called random_stream.sh and remember to save often.

2. Enter the first line of code, which will tell the code where to find the Bash interpreter.

#!/bin/bash

3. Create an array to store all of the possible image effects in this project. There are 20 effects in total, and each has its own place inside the array, enabling our code to pick a specific effect based on a random number.

array[0]="none"
array[1]="negative"
array[2]="solarise"
array[3]="sketch"
array[4]="denoise"
array[5]="emboss"
array[6]="oilpant"
array[7]="hatch"
array[8]="gpen"
array[9]="pastel"
array[10]="watercolour"
array[11]="film"
array[12]="blur"
array[13]="saturation"
array[14]="colourswap"
array[15]="washedout"
array[16]="posterise"
array[17]="colourpoint"
array[18]="colourbalance"
array[19]="cartoon"

4. Create a variable called size to store the number of effects in the array. This variable will store the output of a command (via {})  which checks the length of the array. 

size=${#array[@]}

5. Create another variable, index, which will store a random number between zero and the length of the array, in this case 20. 

index=$(($RANDOM % $size))

6. Print the chosen filter to the terminal, then wait for one second. 

echo ${array[$index]}
sleep 1

7. Use raspivid to create an infinite stream at a resolution of 800 x 600 at 15 fps. The -ifx switch will be populated by a randomly chosen effect from the array To stream live video, this time we use a standard tcp stream. It works a little faster than rstp but your stream may have artefacts. The Pi listens (-l) for connections from any local IP address. 

raspivid -t 0 -w 800 -h 600 -ifx ${array[$index]} -fps 15 -l -o tcp://0. 0.0.0:5000

8. Save the code to the /home/pi/ directory and exit from the editor.

9. Open a terminal and use this command to make the code executable.

$ chmod +x random_stream.sh

10. Run the code.

$ ./random_stream.sh

11. On your Windows / Mac / Linux computer open VLC

12. Go to Media >> Open Network Stream, or press CTRL + N. 

(Image credit: Tom’s Hardware)

13. Enter the tcp address and port of your Raspberry Pi. The tcp address is the Raspberry Pi’s hostname, prefixed with tcp/h364://, and the port set to 5000. Click Play to start the stream. Here is our example tcp address. 

tcp/h364://raspberrypi.local:5000

(Image credit: Tom’s Hardware)

14. To record a stream, click on Playback >> Record and then specify a filename. The recording will end when the stop button is pressed.  

(Image credit: Tom’s Hardware)

15. To change effect, press CTRL + C in the Raspberry Pi terminal, then press the UP key and enter to run the command again, with hopefully a different filter. 

Complete Code Listing 

#!/bin/bash
array[0]="none"
array[1]="negative"
array[2]="solarise"
array[3]="sketch"
array[4]="denoise"
array[5]="emboss"
array[6]="oilpant"
array[7]="hatch"
array[8]="gpen"
array[9]="pastel"
array[10]="watercolour"
array[11]="film"
array[12]="blur"
array[13]="saturation"
array[14]="colourswap"
array[15]="washedout"
array[16]="posterise"
array[17]="colourpoint"
array[18]="colourbalance"
array[19]="cartoon"
size=${#array[@]}
index=$(($RANDOM % $size))
echo ${array[$index]}
sleep 1
raspivid -t 0 -w 800 -h 600 -ifx ${array[$index]} -fps 15 -l -o tcp://0.0.0.0:5000

Join the experts who read Tom’s Hardware for the inside track on enthusiast PC tech news — and have for over 25 years. We’ll send breaking news and in-depth reviews of CPUs, GPUs, AI, maker hardware and more straight to your inbox.

Contact me with news and offers from other Future brandsReceive email from us on behalf of our trusted partners or sponsors

Les Pounder is an associate editor at Tom’s Hardware. He is a creative technologist and for seven years has created projects to educate and inspire minds both young and old. He has worked with the Raspberry Pi Foundation to write and deliver their teacher training program «Picademy».

Video Streaming 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:

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

[email protected]:~ $ 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:

[email protected]:~ $ 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:

[email protected]:~ $ 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><h2>Raspberry Pi - Surveillance Camera</h2></center>
<center><img src="stream. mjpg"></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:

[email protected]:~ $ 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.

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Recommended Resources

What to Read Next…

Enjoyed this project? Stay updated by subscribing our newsletter!

How to use a USB camera with ROS on a Raspberry Pi or BeagleBone Blue — to stream video to a large computer / Sudo Null IT News ) — to read data from the camera through ROS image_view and even broadcast the video stream to a web browser!

At the end of the video is a demonstration on the EduMip robot.

1) As a bonus, we will create a distributed ROS system.

2) Roscore App and Image Viewer App will run on PC (Master) and Camera Node on Raspberry Pi (Slave).

3) To set up master and slave, we need to update environment variables on both devices.

4) On the wizard: find the device’s IP address. For ethernet, net_dev can be either enpXXs0 or ethX:

 $ ifconfig {net_dev}
ifconfig enp61s0
or just ifconfig
 

5) Use the IP address as the value for the ROS_IP variable:

 $ export ROS_IP="10.42.0.1" 

6) And for ROS_MASTER_URI:

 $ export ROS_MASTER_URI="http://10.42.0.1:11311" 

7) If you want to use these values ​​for future sessions, you can store the values ​​in a .bashrc file in your home directory:

 $ echo 'export ROS_IP="10.42.0.1"' >> ~/.bashrc
$ echo 'export ROS_MASTER_URI="http://10.42.0.1:11311"' >> ~/.bashrc 

8) Connect to Raspberry Pi via ssh:

 $ ssh {user}@{raspberry_ip} 

9) For RPi as slave, add Master IP for ROS_MASTER_URI

10) And Raspberry Pi IP for ROS_IP

 $ export ROS_IP="10. 42.0.65"
$ export ROS_MASTER_URI="http://10.42.0.1:11311"
or
$ echo 'export ROS_IP="10.42.0.65"' >> ~/.bashrc
$ echo 'export ROS_MASTER_URI="http://10.42.0.1:11311"' >> ~/.bashrc 

11) Now it’s time to connect the USB camera.

12) Check if the camera is recognized by the system:

 $ lsusb
$ ls /dev | grep video* 

13) Install ROS node usb_cam with required dependencies:

 $ sudo apt install ros-kinetic-usb-cam 

14) The usb_cam node already has a launch test file:

 $ cat /opt/ros/kinetic/share/usb_cam/launch/usb_cam-test.launch 

15) Before running this file, let’s run the ROS kernel on master:

 $ roscore 

16) And now start usb_cam node on slave:

 $ roslaunch usb_cam usb_cam-test.launch 

17) Now we can see the topics created. We can test them either on the master or on the slave.

18) Put the current process in the background with CTRL + Z and issue the bg command to continue running in the background. (on a non-full desktop and no screen version of Ubuntu, just start another terminal)

19) To see the themes in the terminal:

 $ rostopic list 

20)… or in GUI:

 $ rqt_graph 

21) Reading camera data with image_view:

 $ rosrun image_view image_view image:=/usb_cam/image_raw 

22) Or using rqt_image_view

23) Bring background task to foreground:

 $ fg 

24) Last experiment to date — web streaming

25) Installing the ROS node of the web video server:

 $ sudo apt install ros-kinetic-web-video-server 

26) To do this properly, create a catkin workspace for our custom startup file:

 $ mkdir -p ~/rosvid_ws/src
$ cd ~/rosvid_ws
$catkin_make
$ source devel/setup.bash 

27) Then create a ROS package:

 $ cd src
$ catkin_create_pkg vidsrv std_msgs rospy roscpp 

28) Create a launch file with nano, vim etc:

 $ mkdir -p vidsrv/launch
$ nano vidsrv/launch/vidsrv. launch 

put the code from here

On a Beaglebone Blue with an A4Tech usb camera, this code worked for me:

 
  
  
    
    
    
    
    
    
  
  
  
 

29) Assemble the package:

 $ cd ..
$ catkin_make 

30) Start ROS kernel again on master:

 $roscore 

31) And run the created launch file:

 $ roslaunch vidsrv vidsrv.launch 

32) Default web video server port is 8080

33) Open URL in web browser: {RPi_IP}:8080

Documentation links:

→ Video server node
→ USB camera node
→ rqt image viewer
→ Raspberry Pi Camera Module node

You can use almost any USB cameras that have drivers for linux, you can also use the Raspberry Pi Camera Module in the same way link above.

An example of how it works on a BeagleBone Blue with an A4Tech camera:

Search for a troika card on video from a BealeBone Blue USB camera (the recognition algorithm works on a laptop with master ROS).

Setup and examples of MIPI CSI cameras for Raspberry Pi [Ampere / Wiki]

Camera modules connect directly to the VideoCore video chip of Raspberry Pi single-board computers and save Raspberry system resources, while USB ports remain free for other peripherals.

Camera models for Raspberry Pi

  • Official Raspberry Pi High Quality Camera / Documentation

  • Official Raspberry Pi Camera v2 / Documentation

  • Official Raspberry Pi Camera v2 NoIR / Documentation

  • Camera (Model D) / Documentation

  • Camera (Model M) / Documentation

  • Camera (model FPC) / Documentation

  • Camera (Model IR-CUT B) / Documentation

  • Camera (Model Zero) / Documentation

Camera connection

Cameras are sensitive to static electricity. Before working with the module, eliminate your charge — for example, touch a domestic water pipe.

Use the HDMI connection to operate the camera. When working through a virtual desktop (VNC), the window with capturing data from the camera will not be displayed.

  1. Connect camera via FFC/FPC cable to Raspberry Pi in CSI-2 connector:

    1. Official Raspberry Pi High Quality Camera

    2. Official Raspberry Camera v2

    3. Official Raspberry Camera v2 NoIR

    4. Chamber (model D);

    5. Chamber (model M);

    6. Chamber (model FPC);

    7. Camera (Model IR-CUT B);

    8. Camera (Model Zero).

  2. Fire up your Raspberry Pi.

  3. Enter the Raspberry Pi parameter configuration menu:
    Menu
    Preferences
    Raspberry Pi Configuration

  4. Click the Interfaces tab, and then switch the state of the Camera item from Disable to Enable. Save your changes and reboot your Raspberry Pi.

This completes the camera setup and you can safely move on to examples of work.

Examples of work through built-in utilities

The camera is connected and configured — let’s check its capabilities. For testing, we will use the built-in utilities raspistill and raspivid, which are used to capture photos and videos, respectively.

Run all commands in the built-in terminal.

Camera test

Execute the image capture instruction.

 raspistill-t 10000 

The camera feed will appear on the screen for ten seconds. This means that the camera module is operational and ready for operation.

Photo snapshot

Try to take a picture of the camera and save the resulting photo.

Do not reduce the turn-on time of the module to less than two seconds — the camera needs a pause between turning it on and taking a picture. During this time, the module will automatically adjust the white balance and exposure.

Run the command to capture an image and save it to a file on your desktop named image-example.jpg.

 raspistill -t 2000 -o /home/pi/Desktop/image-example.png 

As a result, a photo file from the camera will appear on the desktop.

Video recording

Use the module in video camera mode — shoot a one-minute video and save it with the name video-example.h364.

 raspivid -t 60000 -o /home/pi/Desktop/video-example.h364 

After a minute of waiting, a video file from the camera will appear on the desktop. To watch the video, use the built-in player.

For more information about the built-in utilities for working with the camera, read the documentation from the manufacturer.

Python examples

Experiment with the camera through the Python3 IDE.
You can run the examples through the built-in terminal or the Python IDLE GUI.

Camera test

First, test the camera’s viewfinder.

camera-simple-test.py
 # We connect the necessary libraries
from picamera import PiCamera
from time import sleep

# Create an object to work with the camera
camera = PiCamera()

# Run a preview of the signal from the camera on the screen on top of all windows
camera.start_preview()

# Pause the program for 10 seconds
sleep(10)

# turn off preview
camera.stop_preview() 

The camera image will appear on the screen for ten seconds.

This means that the camera module is operational and ready for operation.

Photo snapshot

Try to take a picture of the camera and save the resulting photo.

Do not reduce the turn-on time of the module to less than two seconds — the camera needs a pause between turning it on and taking a picture. During this time, the module will automatically adjust the white balance and exposure.

camera-save-image.py
 # We connect the necessary libraries
from picamera import PiCamera
from time import sleep

# Create an object to work with the camera
camera = PiCamera()

# Run a preview of the signal from the camera on the screen on top of all windows
camera. start_preview()

# Pause the program for 10 seconds
# Give the camera three seconds to autofocus and set the white balance
sleep(3)

# Take a picture and save it to your desktop as image.jpg
camera.capture('/home/pi/Desktop/image-example.jpg')

# Turn off preview mode
camera.stop_preview() 

As a result, a photo file from the camera will appear on the desktop.

Video recording

Use the module in video camera mode — shoot a one-minute video and save it to your desktop.

camera-save-video.py
 # We connect the necessary libraries
from picamera import PiCamera
from time import sleep

camera = PiCamera()

# Run a preview of the signal from the camera on the screen on top of all windows
camera.start_preview()

# Start recording video file
camera.start_recording('/home/pi/Desktop/video-example.h364')

# Minute write streaming video
camera.wait_recording(60)

# Stop recording
camera.stop_recording()

# turn off preview
camera.