Creating a Camera Stream with Raspberry Pi Zero W and open CV2

Introduction
The Raspberry Pi Zero W is a compact and affordable single-board computer with built-in Wi-Fi and Bluetooth capabilities. One of its exciting features is the ability to connect a camera module and create a live video stream. In this blog post, we'll explore how to set up and stream video from a Raspberry Pi Zero W camera using the picamera library. Refer from here here

Prerequisites
Before getting started, make sure you have the following:

  • Raspberry Pi Zero W board
  • Raspberry Pi Camera Module (any version)
  • MicroSD card with Raspbian OS installed
  • Power supply for Raspberry Pi
  • Access to a terminal or SSH connection to the Raspberry Pi

Setting Up the Raspberry Pi Zero W

  1. Connect Camera Module: First, attach the Raspberry Pi Camera Module to the Raspberry Pi Zero W's camera connector. Be gentle while doing this to avoid damaging the delicate ribbon cable.
  2. Enable Camera Interface: Use raspi-config to enable the camera interface. Open a terminal or SSH into your Raspberry Pi and run the below code. Navigate to "Interfacing Options" > "Camera" and enable the camera interface. Reboot the Raspberry Pi if prompted. Then go to interface > enable legacy camera


sudo raspi-config

  1. Install picamera Library: The picamera library allows us to control the camera module. Install it by running.


sudo pip3 install picamera

Creating the Camera Stream Script
Now, let's create a Python script to capture video from the camera and stream it over a local network.


import io
import time
import json
import urllib
import logging
import cv2  # pip3 install opencv-python
import threading
import socketserver
from http import server
from threading import Condition

MAX_FRAME_TIME_THRESHOLD = 1.0

class StreamingHandler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(301)
            self.send_header('Location', '/stream.mjpg')
            self.end_headers()
        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:
                cap = cv2.VideoCapture(0)  # Use camera index 0 (Raspberry Pi Camera)
                cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
                cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
                cap.set(cv2.CAP_PROP_FPS, 10)
                if not cap.isOpened():
                    logging.warning("Failed to open camera.")
                    return

                while True:
                    start_time = time.time()
                    ret, frame = cap.read()
                    if not ret:
                        continue

                    frame_time = time.time() - start_time
                    if frame_time > MAX_FRAME_TIME_THRESHOLD:
                        continue

                    with io.BytesIO() as output_buffer:
                        _, buffer = cv2.imencode(".jpg", frame)
                        output_buffer.write(buffer)

                        self.wfile.write(b"--FRAME\r\n")
                        self.send_header("Content-Type", "image/jpeg")
                        self.send_header("Content-Length", len(output_buffer.getvalue()))
                        self.end_headers()
                        self.wfile.write(output_buffer.getvalue())
                        self.wfile.write(b"\r\n")

            except Exception as e:
                logging.warning("Removed streaming client %s: %s", self.client_address, str(e))
            finally:
                cap.release()

class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
    allow_reuse_address = True
    daemon_threads = True

if __name__ == "__main__":
    try:
        address = ("", 8080)
        server = StreamingServer(address, StreamingHandler)
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.server_close()

Running the Camera Stream

  1. Save the script to a file named camera_stream.py on your Raspberry Pi.
  2. Open a terminal or SSH into your Raspberry Pi.
  3. Navigate to the directory containing camera_stream.py and run the script.


sudo python3 camera_stream.py

  1. The script will start a web server on port 8000. You can access the camera stream by opening a web browser and navigating to http://raspberrypi.local:8000/.

Conclusion
In this tutorial, we've learned how to create a live camera stream with the Raspberry Pi Zero W using the picamera library. This opens up a world of possibilities for projects such as home surveillance, wildlife monitoring, or simply exploring the capabilities of the Raspberry Pi.

Experiment with different resolutions, framerates, and streaming options to tailor the camera stream to your needs. You can also enhance the web interface with additional HTML, CSS, or JavaScript for a more polished user experience.

The Raspberry Pi Zero W, combined with the Camera Module and picamera library, provides a powerful platform for creating versatile and affordable video streaming applications.

Happy streaming with your Raspberry Pi Zero W camera setup!


ADVERTISEMENT

Previous

Rpi Camera stream using Picamera



Explore these related topics for more information



ADVERTISEMENT
ADVERTISEMENT


ADVERTISEMENT