1、下載YOLOv8模型文件
下載地址:https://docs.ultralytics.com/zh/models/yolov8/#performance-metrics
2、編寫python腳本?aaa.py
import cv2
import numpy as np
from ultralytics import YOLO
import matplotlib.pyplot as pltdef plot_detection(image, boxes, scores, class_ids, class_names, conf_threshold=0.5):"""將檢測結果繪制到圖像上"""# 創建圖像的副本用于繪制img_with_detections = image.copy()# 定義顏色列表,為不同類別使用不同顏色colors = [(0, 255, 0), (255, 0, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]# 遍歷所有檢測結果for i, (box, score, class_id) in enumerate(zip(boxes, scores, class_ids)):# 過濾低置信度的檢測結果if score < conf_threshold:continue# 獲取框的坐標 (x1, y1, x2, y2)x1, y1, x2, y2 = map(int, box)# 選擇顏色 (循環使用顏色列表)color = colors[class_id % len(colors)]# 1. 繪制邊界框cv2.rectangle(img_with_detections, (x1, y1), (x2, y2), color, 2)# 2. 繪制標簽背景label = f"{class_names[class_id]}: {score:.2f}"(label_width, label_height), baseline = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)cv2.rectangle(img_with_detections, (x1, y1 - label_height - 5), (x1 + label_width, y1), color, -1) # -1 表示填充矩形# 3. 繪制標簽文本cv2.putText(img_with_detections, label, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)return img_with_detectionsdef main():# 1. 加載預訓練的 YOLOv8n 模型print("正在加載 YOLOv8n 模型...")model = YOLO('yolov8n.pt') # 會自動下載模型如果不存在# 2. 加載要檢測的圖像image_path = '123.jpg' # 替換為你的圖片路徑print(f"正在加載圖像: {image_path}")image = cv2.imread(image_path)if image is None:print(f"錯誤: 無法加載圖像 {image_path}")return# 3. 進行推理print("正在進行推理...")results = model(image, verbose=False) # verbose=False 減少輸出信息# 4. 提取檢測結果# 獲取第一個結果(因為只輸入了一張圖片)result = results[0]# 提取邊界框信息boxes = result.boxes.xyxy.cpu().numpy() # 邊界框坐標 [x1, y1, x2, y2]scores = result.boxes.conf.cpu().numpy() # 置信度分數class_ids = result.boxes.cls.cpu().numpy().astype(int) # 類別ID# 獲取類別名稱class_names = result.namesprint(class_names)print(f"檢測到 {len(boxes)} 個對象")for i, (box, score, class_id) in enumerate(zip(boxes, scores, class_ids)):print(f"對象 {i+1}: {class_names[class_id]} (置信度: {score:.3f})")# 5. 將檢測結果繪制到圖像上print("正在繪制檢測結果...")result_image = plot_detection(image, boxes, scores, class_ids, class_names)# 6. 保存和顯示結果output_path = 'detection_result123-x.jpg'cv2.imwrite(output_path, result_image)print(f"結果已保存到: {output_path}")# 使用 matplotlib 顯示結果(支持中文顯示)plt.figure(figsize=(12, 8))# 將 BGR 轉換為 RGB 用于 matplotlib 顯示result_image_rgb = cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB)plt.imshow(result_image_rgb)plt.title('YOLOv8 result')plt.axis('off')plt.tight_layout()#plt.savefig('detection_result_plt.jpg', dpi=300, bbox_inches='tight')plt.show()def detect_specific_classes():"""示例:只檢測特定的類別(如可能類似于電表的物體)"""# 可能類似于電表的 COCO 類別target_classes = {67: 'cell phone', # 手機 - 最可能檢測到數字屏幕62: 'tvmonitor', # 顯示器75: 'remote', # 遙控器74: 'clock' # 時鐘}# 加載模型和圖像model = YOLO('yolov8n.pt')image = cv2.imread('your_meter_image.jpg')# 推理results = model(image, verbose=False)result = results[0]# 提取結果boxes = result.boxes.xyxy.cpu().numpy()scores = result.boxes.conf.cpu().numpy()class_ids = result.boxes.cls.cpu().numpy().astype(int)class_names = result.names# 過濾出目標類別filtered_boxes = []filtered_scores = []filtered_class_ids = []for box, score, class_id in zip(boxes, scores, class_ids):if class_id in target_classes and score > 0.3: # 降低閾值filtered_boxes.append(box)filtered_scores.append(score)filtered_class_ids.append(class_id)print(f"檢測到可能的目標: {target_classes[class_id]} (置信度: {score:.3f})")# 繪制結果if filtered_boxes:result_image = plot_detection(image, filtered_boxes, filtered_scores, filtered_class_ids, class_names, conf_threshold=0.3)cv2.imwrite('meter_detection_result.jpg', result_image)print("電表檢測結果已保存")else:print("未檢測到可能的目標物體")if __name__ == "__main__":# 運行主函數進行通用物體檢測main()# 或者運行特定類別檢測(用于電表檢測嘗試)# detect_specific_classes()
3、運行python腳本
python aaa.py
正在加載 YOLOv8n 模型...
正在加載圖像: 10.jpg
正在進行推理...
檢測品類:{0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus', 6: 'train',
7: 'truck', 8: 'boat', 9: 'traffic light', 10: 'fire hydrant', 11: 'stop sign', 12:
'parking meter', 13: 'bench', 14: 'bird', 15: 'cat', 16: 'dog', 17: 'horse', 18: 'sheep',
19: 'cow', 20: 'elephant', 21: 'bear', 22: 'zebra', 23: 'giraffe', 24: 'backpack', 25:
'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31:
'snowboard', 32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove', 36:'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle', 40: 'wine glass', 41:
'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl', 46: 'banana', 47: 'apple', 48:
'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot', 52: 'hot dog', 53: 'pizza', 54:
'donut', 55: 'cake', 56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining
table', 61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard',67: 'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink', 72:
'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors', 77: 'teddy bear', 78:'hair drier', 79: 'toothbrush'}檢測到 2 個對象
對象 1: chair (置信度: 0.968)
對象 2: chair (置信度: 0.946)
正在繪制檢測結果...
結果已保存到: detection_result10.jpg
python腳本、模型文件、圖片文件在一個目錄中
參考官網內容:https://docs.ultralytics.com/zh/models/yolov8/#performance-metrics