Recent Posts
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Today
Total
관리 메뉴

코드민수

[Python] JSON 파일에서 오브젝트 클래스 분석 (히스토그램) 본문

[Python]/코드

[Python] JSON 파일에서 오브젝트 클래스 분석 (히스토그램)

코드민수 2023. 3. 31. 15:01
BIG

객체 탐지(Object Detection) 모델을 학습하기 위해 사용하는 JSON 포맷 라벨 데이터에서

 

각 클래스별 객체 수를 count해서 히스토그램으로 시각화 하는 코드입니다.

import os
import json
import matplotlib.pyplot as plt

path = '경로'  # JSON 파일 있는 경로
classes = {'Glass': 1, 'Metal': 2, 'Wood': 3, 'Plastic': 4, 'Fish_trap': 5,
           'Rubber_tire': 6, 'Rubber_etc': 7, 'Etc': 8}

num = len(classes)
histogram = [0] * num

for file in os.listdir(path):
    with open(os.path.join(path, file), 'r', encoding='utf-8') as f:
        shapes = json.load(f)['shapes']
        for shape in shapes:
            classname = shape['label']
            index = classes.get(classname, num)
            histogram[index - 1] += 1

cls_list = list(classes.keys())

plt.bar(cls_list, histogram, color='navy', width=0.5, zorder=10)
plt.xticks(rotation=45)
plt.title('Objects Histogram', fontdict={'size': 15}, pad=15)
plt.xlabel('Classes', fontdict={'size': 11})
plt.ylabel('Numbers', fontdict={'size': 11})
plt.grid(axis='y', linestyle='--', zorder=1)

plt.tight_layout()
plt.show()

print(histogram)
print('total objects :', sum(histogram))

path와 classes를 데이터셋에 맞게 변경하면 됩니다.

 

출력 결과

LIST