树莓派Camera Module V2扫描条形码失败求助:三种方案均无效
Hey there! Let’s work through your barcode scanning issue step by step. I’ve dealt with similar Raspberry Pi camera barcode setups before, so here’s how to get each of your methods working:
1. Troubleshooting pyzbar
Your current code uses a static image (image.png), which might not reflect the real-time quality from your camera. Common issues here include blurry frames, poor lighting, or the barcode not being centered. Let’s adjust the code to capture live frames and decode them on the fly:
First, install required packages:
pip install picamera pillow pyzbar
Use this updated live-scanning code:
from picamera import PiCamera from PIL import Image import pyzbar.pyzbar as pyzbar import time camera = PiCamera() camera.resolution = (640, 480) camera.start_preview() time.sleep(2) # Let camera warm up try: while True: # Capture a temporary frame temp_image = '/tmp/barcode_temp.png' camera.capture(temp_image) # Load and decode the image image = Image.open(temp_image) codes = pyzbar.decode(image) if codes: for code in codes: print(f"Scanned barcode: {code.data.decode('utf-8')}") print(f"Format: {code.type}") break # Exit after successful scan time.sleep(0.5) finally: camera.stop_preview()
2. Fixing SimpleCV Issues
SimpleCV is outdated and can have compatibility problems with newer Raspberry Pi OS versions. If you still want to use it:
- First, enable your camera via
raspi-config(go to Interface Options > Camera, enable it, then reboot). - Reinstall SimpleCV with updated dependencies:
sudo apt-get install python-opencv python-numpy python-scipy python-pip pip install simplecv - Ensure your user has camera access: run
sudo usermod -a -G video $USER, then log out and back in.
That said, I’d recommend switching to pyzbar or OpenCV methods—SimpleCV isn’t actively maintained anymore.
3. Making OpenCV + Barcode Decoding Work
The tutorial you followed only detects the barcode’s position; you need to add a decoding step to read its content. Here’s how to combine detection with decoding:
First, install required packages:
pip install opencv-python pyzbar numpy
Use this code to detect and decode barcodes:
import cv2 import numpy as np import pyzbar.pyzbar as pyzbar # Initialize camera cap = cv2.VideoCapture(0) cap.set(3, 640) cap.set(4, 480) def detect_barcode(frame): # Convert to grayscale and blur gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (5,5), 0) # Edge detection edges = cv2.Canny(blur, 50, 150) # Find contours contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key=cv2.contourArea, reverse=True)[:5] barcode_contour = None for c in contours: perimeter = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * perimeter, True) if len(approx) == 4: # Barcodes are roughly rectangular barcode_contour = approx break return barcode_contour while True: ret, frame = cap.read() if not ret: break contour = detect_barcode(frame) if contour is not None: # Draw bounding box cv2.drawContours(frame, [contour], -1, (0, 255, 0), 2) # Crop the barcode region x, y, w, h = cv2.boundingRect(contour) barcode_roi = frame[y:y+h, x:x+w] # Decode the barcode codes = pyzbar.decode(barcode_roi) if codes: for code in codes: text = code.data.decode('utf-8') cv2.putText(frame, text, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2) print(f"Decoded: {text}") cv2.imshow('Barcode Scanner', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
General Tips for Success
- Lighting matters: Ensure the barcode is well-lit, with no glare or shadows.
- Adjust focus: Twist the camera lens gently until the barcode appears sharp (the Pi camera has fixed focus).
- Position correctly: Keep the barcode centered, filling 1/3 to 1/2 of the frame.
- Check permissions: Confirm your user is in the
videogroup (runsudo usermod -a -G video $USERand reboot if needed).
内容的提问来源于stack exchange,提问作者Yash Agrawal

