Additional Study/Contest

DCC 클래스별 시각화

생각하는 이상훈 2023. 10. 13. 13:16
728x90

한국 이미지 데이터셋 분류

우선 시각화를 하고 ResNet18을 이용하여 42종의 클래스 분류를 수행하고 Validation 데이터에 대한 정확도를 뽑아보자.


시각화

import zipfile

# 압축 파일의 경로
zip_file_path = 'drive/MyDrive/데이터셋.zip'

# 해당 경로의 압축 파일을 열기
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
    # 현재 디렉토리에 압축 해제
    zip_ref.extractall()

#kfood_train.zip 파일 압축 해제
with zipfile.ZipFile('kfood_train.zip', 'r') as zip_ref:
    zip_ref.extractall()
    
import os
import zipfile
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import random
from PIL import Image

# 이미지 로딩
base_dir = 'train'
class_names = os.listdir(base_dir)
class_names.sort()
sample_images = []

for class_name in class_names:
    class_dir = os.path.join(base_dir, class_name)
    all_images = os.listdir(class_dir)
    sample_image_path = os.path.join(class_dir, random.choice(all_images))
    sample_images.append(Image.open(sample_image_path))

# 이미지 시각화
fig, axs = plt.subplots(7, 6, figsize=(15, 15))
axs = axs.ravel()

for i in range(len(sample_images)):
    axs[i].imshow(sample_images[i])
    axs[i].set_title(str(i+1))  # 여기서 클래스명 대신 숫자를 출력
    axs[i].axis('off')

plt.tight_layout()
plt.show()

한글 폰트가 구글 코랩에서는 깨져서 우선 숫자로 출력을 했으나 한글 폰트를 다운 받아서 한글로 음식이름을 출력하는 코드로 디벨롭하려한다.


한글 출력

아래의 코드를 실행해서 nanum 폰트를 설치했다.

!sudo apt-get install -y fonts-nanum
!sudo fc-cache -fv
!rm ~/.cache/matplotlib -rf

그 결과 아래와 같이 출력되고 이를 이용하여 기존 코드를 조금 수정하면 원하는 결과가 나온다.

import os
import zipfile
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import random
from PIL import Image


font_path = font_path = '/usr/share/fonts/truetype/nanum/NanumGothic.ttf'

font_name = fm.FontProperties(fname=font_path).get_name()
plt.rc('font', family=font_name)

# 이미지 로딩
base_dir = 'train'
class_names = os.listdir(base_dir)
class_names.sort()
sample_images = []

for class_name in class_names:
    class_dir = os.path.join(base_dir, class_name)
    all_images = os.listdir(class_dir)
    sample_image_path = os.path.join(class_dir, random.choice(all_images))
    sample_images.append(Image.open(sample_image_path))

# 이미지 시각화
fig, axs = plt.subplots(7, 6, figsize=(15, 15))
axs = axs.ravel()

for i in range(len(sample_images)):
    axs[i].imshow(sample_images[i])
    axs[i].set_title(class_names[i], fontsize=20)  # 폰트 크기를 조절할 수 있습니다.
    axs[i].axis('off')

plt.tight_layout()
plt.show()

시각화 결과


 

728x90