Raspberry Pi USB Camera Setup (Python + OpenCV Beginner Tutorial)

Опубликовано: 28 Май 2026
на канале: Craftyrobotics
122
3

In this tutorial, we’ll connect a USB camera to a Raspberry Pi and use Python with OpenCV and Matplotlib to display a live video stream. This is a great beginner-friendly project and a solid foundation for computer vision applications like object detection, robotics, and AI projects.

🔧 What you’ll learn:

How to access a USB camera on Raspberry Pi
Capturing live video frames using OpenCV
Converting image formats (BGR → RGB)
Displaying a live video feed using Matplotlib
Creating a simple real-time loop for image updates
How to increase the display size for a better viewing experience

💡 This setup works great for future projects like motion detection, AI-powered wildlife monitoring, or robotics vision systems.

🧠 Python Code (Standard Version):

import cv2
from matplotlib import pyplot as plt

cap = cv2.VideoCapture(0)

plt.ion() # Turn on interactive mode
fig, ax = plt.subplots()
im = None

while True:
ret, frame = cap.read()
if not ret:
print("Failed to grab frame")
break

frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

if im is None:
im = ax.imshow(frame_rgb)
ax.axis('off')
else:
im.set_data(frame_rgb)

plt.pause(0.01) # Small pause to update the figure

Optional: stop loop on keyboard interrupt
try:
plt.gcf().canvas.flush_events()
except KeyboardInterrupt:
break

cap.release()
plt.close()

🖥️ Python Code (Larger Display Version):

import cv2
from matplotlib import pyplot as plt

cap = cv2.VideoCapture(0)

plt.ion() # Turn on interactive mode

fig, ax = plt.subplots(figsize=(10, 6)) # more balanced size
plt.subplots_adjust(left=0, right=1, top=1, bottom=0)

ax.axis('off')

im = None

while True:
ret, frame = cap.read()
if not ret:
print("Failed to grab frame")
break

frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

if im is None:
im = ax.imshow(frame_rgb, aspect='auto')
else:
im.set_data(frame_rgb)

plt.pause(0.01)

try:
plt.gcf().canvas.flush_events()
except KeyboardInterrupt:
break

cap.release()
plt.close()

🚀 Next Steps:

Add object detection (YOLO, TensorFlow Lite, etc.)
Record video or save snapshots
Integrate with a robot or smart system

🌐 Project Page:
https://craftyrobotics.com/

👍 If you found this helpful, don’t forget to like, subscribe, and check out more Raspberry Pi projects!

#RaspberryPi #OpenCV #Python #ComputerVision #Robotics #DIY #TechProjects