统计数据集的TXT、XML及JSON标注文件中各类别/每个标签的数量

在计算机视觉和深度学习领域,标注文件是模型训练的重要组成部分。无论是图像分类、目标检测还是图像分割,正确的标注能够显著提升模型的性能。在实际应用中,我们需要快速了解每个类别的样本数量,以便进行数据分析、平衡类别分布或优化模型训练。

以下是各个格式的文件代码,输出均按照标签数量从多到少排序,其中txt输入需要修改列表中标签。

统计YOLO格式的TXT文件

python 复制代码
import os
from collections import Counter

string_table = ['hat','nohat']  #按顺序修改为类别列表
folder_path = r' '  #修改为txt文件夹
category_counter = Counter()

for filename in os.listdir(folder_path):
    if filename.endswith('.txt'):
        file_path = os.path.join(folder_path, filename)
        with open(file_path, 'r') as file:
            for line in file:
                category_index = int(line.split()[0])
                if category_index < len(string_table):
                    category = string_table[category_index]
                    category_counter[category] += 1
print("各类别数量:")
for category in string_table:
    count = category_counter[category]
    print(f"{category}: {count}")

统计VOC格式的XML文件

python 复制代码
import os
import xml.etree.ElementTree as ET

class_count = {}
folder_path = r' '  # 此处修改为xml文件夹
for filename in os.listdir(folder_path):
	if filename.endswith('.xml'):
		tree = ET.parse(os.path.join(folder_path, filename))
		root = tree.getroot()
		for obj in root.findall('object'):
			name = obj.find('name').text
			if name in class_count:
				class_count[name] += 1
			else:
				class_count[name] = 1
sorted_class_count = sorted(class_count.items(), key=lambda x: x[1], reverse=True)
print("各类别数量:")
for name, count in sorted_class_count:
	print(f"{name}: {count}")

统计JSON文件

python 复制代码
import os
import json
from collections import Counter

json_folder = r' '  # 修改JSON文件夹路径
json_files = [f for f in os.listdir(json_folder) if f.endswith('.json')]
category_counter = Counter()
for json_file in json_files:
    with open(os.path.join(json_folder, json_file), 'r') as f:
        data = json.load(f)
    for shape in data['shapes']:
        category = shape['label']
        category_counter[category] += 1
sorted_category_count = sorted(category_counter.items(), key=lambda x: x[1], reverse=True)
print("各类别数量:")
for category, count in sorted_category_count:
    print(f"{category}: {count}")
相关推荐
qqqahhh2 天前
xml文件的动态化配置,导入
xml·spring·springboot
吴声子夜歌2 天前
Maven——pom.xml详解
xml·java·maven
iSee8573 天前
struts2 XML外部实体注入漏洞复现(CVE-2025-68493)
xml·安全·struts2
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ4 天前
mapper.xml中的大于等于、小于等于
xml
问水っ5 天前
Qt Creator快速入门 第三版 第17-2章 XML
xml
独断万古他化5 天前
【MyBatis 深度解析】注解操作与 XML 配置:增删改查全流程实现
xml·java·spring·mybatis
odoo中国5 天前
如何在 Odoo 19 中加载演示数据
xml·csv·odoo·odoo 19·odoo 演示数据加载
web守墓人7 天前
【前端】ikun-pptx编辑器前瞻问题五:pptx中的xml命名空间
xml·前端
h7ml7 天前
企业微信回调模式解析:从XML到POJO的自定义JAXB编解码器设计
xml·java·企业微信
Full Stack Developme7 天前
达梦(DM8)对 JSON 与 XML 的使用教程
xml·数据库·json