yolo自动生成的指标图
时间: 2025-01-26 13:22:00 浏览: 87
### 自动生成YOLO模型评估指标图表
为了实现YOLO模型自动生成评估指标图表的功能,可以通过编写脚本来处理YOLO模型的预测结果并绘制相应的性能图表。下面是一个完整的Python代码示例,展示了如何读取YOLO模型的结果文件,并利用`matplotlib`库来创建常见的性能对比折线图。
#### 准备环境
确保安装了必要的依赖项:
```bash
pip install matplotlib pandas numpy opencv-python
```
#### 加载YOLO模型及其测试集标注信息
首先加载预训练好的YOLO模型以及对应的测试集标签数据。这里假设已经有一个包含真实框坐标的CSV文件作为ground truth。
```python
import cv2
import torch
from pathlib import Path
import pandas as pd
def load_yolo_model(model_name='yolov5s'):
model = torch.hub.load('ultralytics/yolov5', 'custom', path=model_name, force_reload=True)
return model
def read_ground_truth_labels(file_path):
df = pd.read_csv(file_path)
return df[['image_id', 'class_id', 'xmin', 'ymin', 'xmax', 'ymax']]
```
#### 进行推断并将结果保存到DataFrame中
接下来执行图像上的目标检测操作,并收集所有预测边界框的信息存入Pandas DataFrame结构内以便后续统计分析。
```python
def infer_images(image_dir, ground_truth_df, yolo_model):
results_list = []
for img_file in image_dir.glob('*.jpg'):
im = cv2.imread(str(img_file))
detections = yolo_model(im).pandas().xyxy[0]
# Match detected objects with GT by IoU threshold (e.g., 0.5)
matched_detections = match_predictions_with_gt(detections, ground_truth_df)
result_row = {
"filename": str(img_file),
**matched_detections.describe(),
}
results_list.append(result_row)
return pd.DataFrame(results_list)
def match_predictions_with_gt(pred_boxes, gt_boxes):
from scipy.spatial.distance import cdist
ious = calculate_ious(pred_boxes.values[:, :4], gt_boxes.values[:, 2:])
best_matches_idx = ious.argmax(axis=1)[iou_threshold >= 0.5]
pred_matched = pred_boxes.iloc[best_matches_idx].copy()
pred_unmatched = pred_boxes.drop(best_matches_idx).reset_index(drop=True)
return pred_matched.assign(is_true_positive=lambda r: True)\
.append(pred_unmatched.assign(is_true_positive=False), ignore_index=True)
def calculate_ious(boxes_a, boxes_b):
"""Calculate intersection over union between two sets of bounding boxes."""
areas_a = area_of(boxes_a[:, 0], boxes_a[:, 1],
boxes_a[:, 2], boxes_a[:, 3])
areas_b = area_of(boxes_b[:, 0], boxes_b[:, 1],
boxes_b[:, 2], boxes_b[:, 3])
inter_x_min = np.maximum(boxes_a[:, None, 0], boxes_b[:, 0])
inter_y_min = np.maximum(boxes_a[:, None, 1], boxes_b[:, 1])
inter_x_max = np.minimum(boxes_a[:, None, 2], boxes_b[:, 2])
inter_y_max = np.minimum(boxes_a[:, None, 3], boxes_b[:, 3])
inters = ((inter_x_max - inter_x_min).clip(min=0) *
(inter_y_max - inter_y_min).clip(min=0))
unions = areas_a[:, None] + areas_b - inters
return inters / unions
def area_of(left_top, right_bottom):
hw = np.clip(right_bottom - left_top, min=0.0)
return hw[..., 0] * hw[..., 1]
```
#### 绘制性能曲线
最后一步是从上述整理的数据集中提取关键评价指标(如mAP),并通过Matplotlib可视化这些数值变化趋势。
```python
import matplotlib.pyplot as plt
def plot_performance_curve(df_results, output_fig=None):
fig, ax = plt.subplots(figsize=(8,6))
ap_values = compute_average_precision(df_results)
ax.plot(ap_values.index.tolist(), ap_values.values.tolist())
ax.set_title('Average Precision per Class')
ax.set_xlabel('Class Index')
ax.set_ylabel('Precision Value')
if output_fig is not None:
plt.savefig(output_fig)
else:
plt.show()
def compute_average_precision(df_results):
grouped_by_class = df_results.groupby(['class_id'])
precisions_per_class = {}
for class_id, group_data in grouped_by_class:
tp_count = sum(group_data['is_true_positive'] == True)
fp_count = len(group_data[group_data['is_true_positive'] == False])
recall = tp_count / max(len(group_data), 1e-9)
precision = tp_count / float(tp_count + fp_count + 1e-9)
precisions_per_class[class_id] = precision
return pd.Series(precisions_per_class)
```
此过程涵盖了从准备环境、加载模型和测试集标签、进行推理得到预测结果直到最终绘制成图表的一系列步骤[^1]。通过这种方式可以方便快捷地生成类似于学术界发布的那些高质量的目标检测算法性能比较图形化展示材料。
阅读全文
相关推荐


















