import os
import json
# 获取包含JSON文件的目录列表
root_dir = 'C:/Users/xu\'xu/Desktop/prepare/dataset/JPEGImages'
json_files = [f for f in os.listdir(root_dir) if f.endswith('.json')] # 获取文件名
# 统计每个类别出现的数量
categories_count = {}
for json_file in json_files:
with open(os.path.join(root_dir, json_file), 'r') as f:
data = json.load(f)
for annotation in data['shapes']:
category_name = annotation['label']
# category_name = data['categories'][category_id]['name']
# if category_name not in categories_count:
# categories_count[category_name] = 0
if (category_name in categories_count.keys()):
categories_count[category_name] += 1 # 如果标签不是第一次出现,则+1
else:
categories_count[category_name] = 1
# 输出结果
print("标签名称\t数量")
for category, count in categories_count.items():
print(f"{category}\t{count}")
代码中的json.load() 该函数需要一个打开的文件句柄作为输入,并返回Python对象
如上图所示,为了获取label对应的值就需要在多层嵌套中使用索引符[]
,递归地遍历对象并获取所有想要的数据
运行结果部分显示如下:
标签名称 数量
capillary 24
frayed edge 86
pit 61