Picamera2报错:'numpy.ndarray'对象无'read'属性的技术问询
PiCam3迁移目标检测追踪代码的报错解决
核心问题原因
你遇到的AttributeError: 'numpy.ndarray' object has no attribute 'read'和numpy安装完全无关——教程里能用是因为它用普通USB摄像头的OpenCV调用(cv2.VideoCapture(0)),返回的是VideoCapture对象,所以支持.read()方法;但PiCam的capture_array()直接返回numpy数组格式的帧,数组本身没有.read()方法,这才是报错根源。
代码对比与修正
教程可用代码(示例)
import cv2 from tracker import Tracker # USB摄像头返回VideoCapture对象,支持.read() cap = cv2.VideoCapture(0) tracker = Tracker() while True: # 调用对象的.read()获取帧 ret, frame = cap.read() # 目标检测逻辑(示例) detections = [] # 替换为实际检测代码,比如从模型输出提取bounding box # ... tracker.update(frame, detections) # 绘制框和ID for track in tracker.tracks: bbox = track.bbox cv2.rectangle(frame, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0,255,0), 2) cv2.putText(frame, str(track.id), (bbox[0], bbox[1]-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2) cv2.imshow("Frame", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
你的错误代码(示例)
from picamera2 import Picamera2 import cv2 from tracker import Tracker picam2 = Picamera2() picam2.configure(picam2.create_preview_configuration(main={"format": "RGB888", "size": (640, 480)})) picam2.start() # 直接获取numpy数组格式的帧 frame = picam2.capture_array() tracker = Tracker() while True: # 错误:numpy数组没有.read()方法 ret, frame = frame.read() # 后续检测追踪逻辑 # ...
修正后的PiCam代码
from picamera2 import Picamera2 import cv2 from tracker import Tracker picam2 = Picamera2() # 配置摄像头输出RGB格式,和OpenCV兼容 picam2.configure(picam2.create_preview_configuration(main={"format": "RGB888", "size": (640, 480)})) picam2.start() tracker = Tracker() while True: # 直接捕获numpy数组帧,无需.read() frame = picam2.capture_array() # 保留教程中的目标检测逻辑 detections = [] # 替换为你的实际检测代码,比如YOLO模型推理 # results = model(frame) # for result in results: # x1, y1, x2, y2 = result.boxes.xyxy[0].tolist() # detections.append([x1, y1, x2, y2]) tracker.update(frame, detections) # 绘制bounding box与ID for track in tracker.tracks: bbox = track.bbox # 转换为整数,避免OpenCV报错 cv2.rectangle(frame, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), (0, 255, 0), 2) cv2.putText(frame, str(track.id), (int(bbox[0]), int(bbox[1]) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.imshow("PiCam Vehicle Tracking", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break picam2.stop() cv2.destroyAllWindows()
关键说明
- 无需额外安装numpy:PiCam的
capture_array()依赖numpy返回数组,且OpenCV本身也依赖numpy,你的环境中肯定已存在该库,报错和numpy无关。 - PiCam帧获取逻辑:循环调用
capture_array()即可持续获取实时帧,不需要像USB摄像头那样用.read()。
报错信息
AttributeError: 'numpy.ndarray' object has no attribute 'read'
内容的提问来源于stack exchange,提问作者user24088758
相关产品推荐
相关产品推荐

