You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何修改树莓派Python人脸识别代码以从CSI摄像头切换为USB摄像头

How to Adapt the face_recognition Raspberry Pi CSI Camera Example for USB Webcams

I'm using the facerec_on_raspberry_pi.py example from the face_recognition repo on my Raspberry Pi, which works perfectly with the CSI camera. How can I modify it to work with a USB webcam instead?

Great question! The original script relies on picamera, which only supports Raspberry Pi's native CSI camera modules. To switch to a USB webcam, we'll use OpenCV for video capture instead—here's a step-by-step solution:

Step 1: Install Required Dependencies

First, install OpenCV to handle USB webcam input:

pip install opencv-python

Step 2: Modified Code for USB Webcams

Replace your original facerec_on_raspberry_pi.py with this updated version:

# This is a demo of running face recognition on a Raspberry Pi with a USB webcam.
# This program will print out the names of anyone it recognizes to the console.
# To run this, you need a Raspberry Pi 2 (or greater) with face_recognition and
# opencv-python installed.
import face_recognition
import cv2
import numpy as np

# Get a reference to the USB webcam.
# 0 is usually the default device index for the first USB webcam.
# If it doesn't work, try changing to 1, 2, etc.
video_capture = cv2.VideoCapture(0)

# Set the resolution (matches the original CSI camera settings)
video_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
video_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)

# Load a sample picture and learn how to recognize it.
print("Loading known face image(s)")
obama_image = face_recognition.load_image_file("obama_small.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]

# Initialize some variables
face_locations = []
face_encodings = []

while True:
    print("Capturing image.")
    # Grab a single frame of video from the USB webcam
    ret, frame = video_capture.read()
    
    # Ensure we successfully captured a frame (prevents errors if webcam disconnects)
    if not ret:
        print("Failed to capture frame. Exiting...")
        break

    # Convert image from BGR (OpenCV's default) to RGB (face_recognition's required format)
    rgb_frame = frame[:, :, ::-1]

    # Find all faces and face encodings in the current frame
    face_locations = face_recognition.face_locations(rgb_frame)
    print("Found {} faces in image.".format(len(face_locations)))
    face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)

    # Check each face against known encodings
    for face_encoding in face_encodings:
        match = face_recognition.compare_faces([obama_face_encoding], face_encoding)
        name = "<Unknown Person>"

        if match[0]:
            name = "Barack Obama"

        print("I see someone named {}!".format(name))

# Clean up: Release the webcam connection when done
video_capture.release()

Key Changes Explained

  • Replaced picamera with cv2.VideoCapture: OpenCV's VideoCapture supports USB webcams. Use index 0 for the first connected camera; if you have multiple devices, try 1 or 2 instead.
  • Frame Format Conversion: OpenCapture captures frames in BGR color, but face_recognition expects RGB. We fix this with rgb_frame = frame[:, :, ::-1].
  • Frame Validation: Added a check for ret to avoid crashes if the webcam fails to capture a frame.
  • Proper Cleanup: Added video_capture.release() to close the webcam connection gracefully when the loop exits.

Troubleshooting Tip

If the webcam isn't detected, list connected video devices to confirm the correct index:

ls /dev/video*

内容的提问来源于stack exchange,提问作者Pavol Bujna

火山引擎 最新活动