Beginner Tutorial: How to Stream Video from Raspberry Pi Camera to Local Computer using Python (P1)

 
Learn how to set up a Flask App on your Raspberry Pi and create a live video feed that you can access on your local network, creating a real-time security camera. You will be able to view the video stream over the internet on your local network by the end of this video! All you will need is a Raspberry Pi (I used a 4b), a camera, and a power supply.
Before reading the remainder, be sure to subscribe and support the channel if you have not!
Subscribe:
Support:
Hire me at UpWork to build your IoT projects:

1-) Download Packages on Raspberry Pi

In this section, we'll prepare your Raspberry Pi for camera streaming by installing necessary packages, enabling the camera, and configuring network settings. Follow these steps in the terminal of your Raspberry Pi:

Update Package Lists

First, ensure your package lists are up-to-date to avoid any compatibility issues during installation. Run the following command:
sudo apt update

Enable Camera Interface

Next, we need to enable the camera interface on your Raspberry Pi. This can be done through the Raspberry Pi configuration tool. Enter the following command:
sudo raspi-config
Navigate to the Interface Options, select Camera, and choose <Yes> to enable it. Once this is done, you'll have to restart your Raspberry Pi for the changes to take effect.

Install Flask and PiCamera

With the camera enabled, we'll now install Flask, a micro web framework for Python, and PiCamera, the Python library for Raspberry Pi camera module. You can use pip (Python's package installer) for this. If you're using Python 3 (recommended), you can install these packages with the following command:
pip3 install flask picamera
If you don’t have pip3 installed, you can install it first by running:
sudo apt install python3-pip

Retrieve Your Raspberry Pi's IP Address

Lastly, you'll need the IP address of your Raspberry Pi to access the camera stream from other devices on your local network. Retrieve the IP address by running:
ifconfig
Note down the IP address displayed under the wlan0 section (for wireless connection) or eth0 section (for wired connection). You'll use this IP address to connect to your Raspberry Pi camera stream from your local network.

2-) Code Overview

Now that you have the setup, create a python script and name it whatever you like on your local computer, run the following code:

import io
import picamera
from flask import Flask, Response

### You can donate at https://www.buymeacoffee.com/mmshilleh if I saved you time
### Subscribe https://www.youtube.com/@mmshilleh/videos

app = Flask(__name__)

def generate_frames():
with picamera.PiCamera() as camera:
camera.resolution = (640, 480)
camera.framerate = 24
stream = io.BytesIO()

for _ in camera.capture_continuous(stream, 'jpeg', use_video_port=True):
stream.seek(0)
yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + stream.read() + b'\r\n'
stream.seek(0)
stream.truncate()

@app.route('/video_feed')
def video_feed():
return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, threaded=True)
This script is designed to set up a simple web server that streams live video from a camera connected to a Raspberry Pi. Here's a breakdown of its components and what each part does:
Imports:
  • io and picamera are used to interact with the Raspberry Pi's camera module.
  • Flask is a micro web framework in Python, used here to handle web server operations.
    Flask App Initialization:
    • app = Flask(__name__) initializes the Flask application.
    Frame Generation Function (generate_frames):
    • This function interacts with the PiCamera to capture video frames.
    • camera.resolution and camera.framerate are set to define the quality and frame rate of the video.
    • It captures frames continuously in a loop using camera.capture_continuous.
    • Each frame is converted to a JPEG image and formatted as a multipart message (a standard way to transmit binary data over HTTP). This allows each frame to be sent over the internet immediately after it's captured.
      Web Server Route (/video_feed):
      • The @app.route('/video_feed') decorator tells Flask that any HTTP request to the '/video_feed' URL should be handled by the video_feed function.
      • The video_feed function returns a streaming response generated by generate_frames. The mimetype parameter tells the browser how to interpret the data it's receiving.
        Main Block:
        • The if __name__ == '__main__': block ensures that the web server is started only if this script is executed as the main program.
        • app.run(host='0.0.0.0', port=5000, threaded=True) starts the Flask application. It listens on all public IPs (0.0.0.0) at port 5000 and handles requests in a separate thread for each incoming request, allowing multiple clients to view the stream simultaneously.
        When you run this script on your Raspberry Pi, it starts a web server. You can view the live video stream by navigating to
        http://<your-pi's-IP-address>:5000/video_feed
        in a web browser. The video is streamed in real-time, so this could be used for monitoring, video conferencing, or just sharing what your camera sees with others over the web.

        Conclusion

        Hope you enjoyed the tutorial! If you did, be sure to subscribe to the YouTube channel in the video above. Let me know if you have any questions. I will see you in Part 2 where we go over how to create a video stream you can view from anywhere, beyond your local network, so stay tuned.

        Create a free account to access full content.

        All access to code and resources on ShillehTek.

        Signup Now

        Already a member? Sign In

        Explore More on Our Blog

        Controlling a 5V Laser Diode with Raspberry Pi Pico W

        Controlling a 5V Laser Diode with Raspberry Pi Pico W

        Learn how to safely control high-power components like a ShillehTek 5V laser diode using the Raspberry Pi Pico W and...

        How to Connect and Use the HCSR501 PIR Sensor with a Raspberry Pi Pico/Pico W

        How to Connect and Use the HCSR501 PIR Sensor with a Raspberry Pi Pico/Pico W

        Learn how to set up the HCSR501 PIR sensor with a Raspberry Pi Pico to detect motion and trigger...

        Powering the Raspberry Pi Pico W with the MB102 Power Supply

        Powering the Raspberry Pi Pico W with the MB102 Power Supply

        Learn how to power your Raspberry Pi Pico W projects easily and flexibly with the MB102 Power Supply Module...

        How to Use L298N Motor Driver with Pico W

        How to Use L298N Motor Driver with Pico W

        Learn how to use the L298N motor driver to control DC motors with the Raspberry Pi Pico W in MicroPython.

        Controlling an LED with a Snap Using the KY-037 Sound Sensor and Raspberry Pi

        Controlling an LED with a Snap Using the KY-037 Sound Sensor and Raspberry Pi

        Discover how to set up, code, and activate the LED based on detected sound with the Raspberry Pi...

        Getting Started with the KY-037 Sound Sensor and Raspberry Pi: Detecting Sound Using Python

        Getting Started with the KY-037 Sound Sensor and Raspberry Pi: Detecting Sound Using Python

        In this tutorial, I’ll guide you through setting up the KY-037 sound sensor with a Raspberry Pi using...

        How to Post to Reddit Using Python

        How to Post to Reddit Using Python

        Post to reddit automatically using a Python script.

        How to Create a Time-Lapse Video with a Raspberry Pi Camera

        How to Create a Time-Lapse Video with a Raspberry Pi Camera

        Learn how to make a timelapse with your Raspberry Pi in Python.

        How to Integrate the MPU6050 with the STM32 Blue Pill

        How to Integrate the MPU6050 with the STM32 Blue Pill

        Learn how to measure acceleration with the STM32 and the MPU6050 in the Arduino IDE.

        Getting Started with STM32 Blue Pill in Arduino IDE Using a USB to TTL Converter — Write Your First Program

        Getting Started with STM32 Blue Pill in Arduino IDE Using a USB to TTL Converter — Write Your First Program

        This comprehensive tutorial will guide you through the process of setting up and programming the STM32 Blue Pill...

        Back to blog

        Leave a comment

        Please note, comments need to be approved before they are published.