统计labelme标注的json文件中各类别的标注数量
import os
import json
from collections import defaultdictdef count_bboxes_by_class(folder_path):"""统计文件夹中所有JSON文件中各类别对应的框数量参数:folder_path: 包含JSON文件的文件夹路径返回:字典,键为类别标签,值为对应的框数量"""# 初始化计数器class_bbox_count = defaultdict(int)# 检查文件夹是否存在if not os.path.exists(folder_path):print(f"错误:文件夹 {folder_path} 不存在")return class_bbox_count# 遍历文件夹中的所有文件for filename in os.listdir(folder_path):if filename.endswith('.json'):file_path = os.path.join(folder_path, filename)try:# 读取JSON文件with open(file_path, 'r', encoding='utf-8') as f:data = json.load(f)# 检查文件中是否包含shapes字段if 'shapes' in data:# 统计每个类别的框数量for shape in data['shapes']:class_label = shape['label']class_bbox_count[class_label] += 1print(f"已处理文件: {filename}")except json.JSONDecodeError:print(f"警告:无法解析JSON文件 {filename}")except Exception as e:print(f"处理文件 {filename} 时发生错误: {str(e)}")return class_bbox_countdef print_statistics(class_bbox_count):"""打印统计结果"""if not class_bbox_count:print("未找到任何类别框统计信息")returnprint("\n类别框数量统计结果:")print("=" * 40)print(f"{'类别标签':<15}{'框数量':<15}")print("-" * 40)for class_label, count in class_bbox_count.items():print(f"{class_label:<15}{count:<15}")total = sum(class_bbox_count.values())print("-" * 40)print(f"{'总计':<15}{total:<15}")if __name__ == "__main__":folder_path = "path/to/jsonFolder"# 统计类别框数量class_bbox_count = count_bboxes_by_class(folder_path)# 打印统计结果print_statistics(class_bbox_count)
其中folder_path是集中存放json的文件夹目录