如何修改树莓派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.pyexample 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
picamerawithcv2.VideoCapture: OpenCV'sVideoCapturesupports USB webcams. Use index0for the first connected camera; if you have multiple devices, try1or2instead. - Frame Format Conversion: OpenCapture captures frames in BGR color, but
face_recognitionexpects RGB. We fix this withrgb_frame = frame[:, :, ::-1]. - Frame Validation: Added a check for
retto 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




