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:
Setting Up the Raspberry Pi Zero W
sudo raspi-config
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
sudo python3 camera_stream.py
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!
Explore these related topics for more information