如何统计YOLO数据集各个类别的图片数量并画出曲线图
时间: 2025-06-28 19:12:40 浏览: 4
### 计算YOLO数据集中类别数量并绘制折线图
对于YOLO数据集中的每一类,可以通过读取标注文件来统计各类别对应的图像数量。通常情况下,YOLO格式的数据集会有一个或多个`.txt`文件作为标注文件,其中包含了每个对象的位置以及所属的类别ID。
为了实现这一目的,可以编写一段Python脚本来遍历所有的标注文件,并记录下各个类别的出现次数。之后利用Matplotlib库将这些统计数据转换成直观易懂的折线图展示出来[^1]。
#### Python代码示例:统计YOLO数据集中每种类别的图片数量并绘制折线图
```python
import os
from collections import Counter
import matplotlib.pyplot as plt
def count_classes_in_yolo_dataset(labels_dir):
"""
统计YOLO数据集中每个类别的实例数
:param labels_dir: YOLO标签文件所在的目录路径
:return: 各个类别的实例数目字典
"""
class_counts = Counter()
# 遍历labels_dir下的所有.txt文件
for label_file in os.listdir(labels_dir):
if not label_file.endswith('.txt'):
continue
with open(os.path.join(labels_dir, label_file)) as f:
lines = f.readlines()
for line in lines:
parts = line.strip().split()
if len(parts) >= 1:
class_id = int(float(parts[0]))
class_counts[class_id] += 1
return dict(class_counts)
# 假设label_files_path为你保存YOLO标签文件(.txt)的文件夹路径
label_files_path = 'path/to/your/yolo_labels'
class_instance_numbers = count_classes_in_yolo_dataset(label_files_path)
# 对类别按编号从小到大排序
sorted_class_ids = sorted(class_instance_numbers.keys())
counts = [class_instance_numbers[id_] for id_ in sorted_class_ids]
plt.figure(figsize=(8, 6))
plt.plot(sorted_class_ids, counts, marker='o')
plt.xticks(ticks=range(min(sorted_class_ids), max(sorted_class_ids)+1))
# 设置字体样式以便更好地呈现中文字符
plt.rcParams['font.sans-serif']=['SimSun']
plt.rcParams['axes.unicode_minus']=False
plt.title('YOLO 数据集中各分类的数量分布', fontsize=14)
plt.xlabel('类别 ID', fontsize=12)
plt.ylabel('样本数量', fontsize=12)
for i, cnt in enumerate(counts):
plt.text(i, cnt+5, str(cnt), ha='center')
plt.grid(True)
plt.tight_layout()
plt.show()
```
此段代码首先定义了一个函数用于扫描指定目录内的所有YOLO格式的标签文件,并通过逐行解析的方式获取每一个物体所关联的类别索引;接着使用内置模块`collections.Counter()`来进行高效的频次统计工作。最后借助于Matplotlib的强大绘图功能把得到的结果以折线的形式展现给用户查看[^2]。
阅读全文
相关推荐

















