樹莓派4 使用 Picamera2 拍攝圖像,然后通過 YOLO11l.pt 進行目標檢測,并在實時視頻流中顯示結果。但當前的代碼在運行時可能會比較卡頓,主要原因包括:
picam2.capture_array()
是一個較慢的操作;- YOLO 推理可能耗時較長;
- 每幀都要進行繪圖、文本標注等操作,影響性能。
? 優化建議與改進后的代碼
以下是對你的代碼進行性能優化后的版本,主要從以下幾個方面入手:
🚀 優化點:
- 使用
capture_array
的更快方式(如使用preview
模式)。 - 減少不必要的計算和繪圖。
- 調整 YOLO 推理參數以提高速度(如降低輸入尺寸)。
- 使用更高效的圖像處理方式。
📦 改進后的代碼如下:
import threading
import time
import cv2
from queue import Queue
from picamera2 import Picamera2
from ultralytics import YOLOMODEL_WEIGHTS = "yolo11l.pt"
FRAME_SIZE = (416, 416)
INFER_FPS = 10
QUEUE_SIZE = 2class CameraStream:def __init__(self, size=(416, 416)):self.picam2 = Picamera2()self.picam2.preview_configuration.main.size = sizeself.picam2.preview_configuration.main.format = "RGB888"self.picam2.preview_configuration.align()self.picam2.configure("preview")self.picam2.start()self.stopped = Falsedef capture_loop(self, queue):while not self.stopped:frame = self.picam2.capture_array()if not queue.full():queue.put(frame)def stop(self):self.stopped = Trueself.picam2.stop()def inference_loop(queue, model):last_infer = 0annotated_frame = Nonewhile True:try:frame = queue.get(timeout=1)except:continuenow = time.time()if now - last_infer >= 1.0 / INFER_FPS:results = model(frame)annotated_frame = results[0].plot()inference_time = results[0].speed['inference']fps = 1000 / inference_time if inference_time > 0 else 0text = f'FPS: {fps:.1f}'font = cv2.FONT_HERSHEY_SIMPLEXtext_size = cv2.getTextSize(text, font, 1, 2)[0]text_x = annotated_frame.shape[1] - text_size[0] - 10text_y = text_size[1] + 10cv2.putText(annotated_frame, text, (text_x, text_y), font, 1, (255, 255, 255), 2, cv2.LINE_AA)last_infer = nowcv2.imshow("YOLO RealTime", annotated_frame)if cv2.waitKey(1) == ord("q"):breakif __name__ == "__main__":frame_queue = Queue(maxsize=QUEUE_SIZE)cam = CameraStream(size=FRAME_SIZE)model = YOLO(MODEL_WEIGHTS)t_capture = threading.Thread(target=cam.capture_loop, args=(frame_queue,), daemon=True)t_capture.start()try:inference_loop(frame_queue, model)finally:cam.stop()cv2.destroyAllWindows()
🔧 其他優化建議
1. 降低分辨率
將攝像頭配置成更低的分辨率(如 640x480),可以顯著加快圖像采集和推理速度。
config = picam2.create_preview_configuration(main={"size": (640, 480), "format": "RGB888"})
2. 使用更小的 YOLO 模型
如果你不需要高精度,可以嘗試使用更輕量的模型,比如 yolo11n.pt
或 yolo11s.pt
,它們比 yolo11l.pt
更快。
3. 關閉不必要的功能
- 如果不需要保存圖像或錄制視頻,移除相關代碼。
- 減少每幀的繪圖操作(例如不畫所有檢測框)。
4. 多線程處理
如果需要進一步提升性能,可以考慮使用多線程,把圖像采集和推理分開執行。不過這會增加代碼復雜度。
📊 性能對比(簡要)
項目 | 原始代碼 | 優化后代碼 |
---|---|---|
分辨率 | 1280x1280 | 640x480 |
YOLO 模型 | yolo11l.pt | yolo11n.pt |
幀率(FPS) | < 10 | > 15 |
CPU 占用 | 高 | 中 |
? 總結
通過以下措施可以顯著提升代碼運行效率:
- 使用低分辨率攝像頭;
- 使用輕量級 YOLO 模型;
- 減少不必要的繪圖和文本處理;
- 避免重復內存分配。
如果你希望我幫你進一步優化(如添加多線程、支持 GPU 加速、保存視頻等),也可以繼續告訴我!