Python 统计YOLO(txt)格式标签中各类别样本数

代码如下:(自用)

import os

txt_path = r'E:\Downloads\mask_yolo_853_tra80\YOLOLabels\\'  # txt文件所在路径
class_num = 3  # 样本类别数
class_list = [i for i in range(class_num)]
class_num_list = [0 for i in range(class_num)]
labels_list = os.listdir(txt_path)
for i in labels_list:
    file_path = os.path.join(txt_path, i)
    file = open(file_path, 'r')  # 打开文件
    file_data = file.readlines()  # 读取所有行
    for every_row in file_data:
        class_val = every_row.split(' ')[0]
        class_ind = class_list.index(int(class_val))
        class_num_list[class_ind] += 1
    file.close()
# 输出每一类的数量以及总数
print(class_num_list)
print('total:', sum(class_num_list))

### YOLO Txt Label 文件格式 YOLO标签文件采用 `.txt` 格式每个对象占一行记录。每行由五个数值组成,分别是类别编号以及边界框的位置参数: - 类别编号(class id):表示物体所属类别的索引值,从 `0` 开始计数。 - 边界框中心点坐标(x_center, y_center):相对于图片宽度和高度的比例位置,取值范围为 `[0.0, 1.0]`。 - 宽高比例(width_ratio, height_ratio):同样基于图像尺寸计算得到的相对宽高。 具体来说,对于一张分辨率为 W×H 的图片而言,如果有一个目标位于 `(xmin,ymin)` 到 `(xmax,ymax)` 范围内,则对应的 txt 文件内容应如下所示[^1]: ```plaintext <class_id> <(xmin+xmax)/2/W> <(ymin+ymax)/2/H> <(xmax-xmin)/W> <(ymax-ymin)/H> ``` 例如,假设有一张大小为 640x480 像素的照片,在其中检测到一只猫占据左上角区域 (50,70)-(150,200),而 cats 对应在 classes.txt 中的第一位(即 index=0),那么相应的 txt 记录将是这样一条语句: ```plaintext 0 0.125 0.3958333333333333 0.15625 0.2708333333333333 ``` 这种紧凑且易于解析的数据结构使得 YOLO 模型能够高效读入并处理大量样本信息。 #### 示例代码展示如何生成上述格式标签文件 下面给出一段简单的 Python 代码片段用于创建符合 YOLO 规范的标签文件[^2]: ```python def convert_bbox_to_yolo(image_width, image_height, bbox): """ 将 PASCAL VOC 或其他形式的 bounding box 转换成 YOLO 所需格式 参数: image_width -- 图片宽度 image_height -- 图片高度 bbox -- list or tuple of four elements [xmin, ymin, xmax, ymax] 返回: str -- 符合 YOLO 标签格式的一行字符串 """ dw = 1./image_width dh = 1./image_height x_center = (bbox[0] + bbox[2]) / 2.0 * dw y_center = (bbox[1] + bbox[3]) / 2.0 * dh width_ratio = (bbox[2] - bbox[0]) * dw height_ratio = (bbox[3] - bbox[1]) * dh return f"{int(class_id)} {round(x_center, 6)} {round(y_center, 6)} {round(width_ratio, 6)} {round(height_ratio, 6)}" ```
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值