22.02.22 [kfood프로젝트] 정제한 음식 사진(aihub 데이터셋 2개 합침) bounding box그리기 - .json과 .properties파일 읽기

2022. 2. 22. 19:59프로젝트/KFood

step_4 최종 bbox 확인

데이터셋 폴더 kfood_sy

import random
from matplotlib import pyplot as plt
import cv2
import numpy as np
from PIL import Image
import os
import json

# jupyter notebook 내 그래프를 바로 그리기 위한 설정
%matplotlib inline
# unicode minus를 사용하지 않기 위한 설정 (minus 깨짐현상 방지)
plt.rcParams['axes.unicode_minus'] = False
# 나눔고딕 폰트 적용
plt.rcParams['font.family'] = 'Malgun Gothic'

count=1
 
plt.figure('seoyoon',figsize = (30,50))
# plt.figure('seoyoon').clf()


for i in os.listdir('./kfood_sy'):
    for j in os.listdir(f'./kfood_sy/{i}'):
        print(j)
        plt.subplot(11,3,count)
        img_list= os.listdir(f'./kfood_sy/{i}/{j}/image')
        # print(img_list[:10])
        
        # 랜덤으로 이미지 한개 뽑기 
        choice = random.choice(img_list) 
        print(choice) # 'B080285XX_02222.jpg' 또는 'Img_133_0310.jpg'
        
        #  PIL Image를 numpy array 처리
        img = Image.open(f'./kfood_sy/{i}/{j}/image/'+choice) # 뽑은 이미지 1개 PIL로 읽기
        imgArray = np.array(img) 
        img_shape = imgArray.shape 
        print(imgArray.shape) # (1800, 2700, 3) = (H,W,channel수)
        
        # case1 : json
        if 'Img'  not in choice:
            with open(f'./kfood_sy/{i}/{j}/label/'+choice[:-4]+'.json',mode='r',encoding='UTF8') as f:
                data = json.load(f)
                print(data[0])
                print(json.dumps(data, indent="\t") ) # json을 더 예쁘게 출력하기 위한 
            x_center = float(data[0]['Point(x,y)'].split(',')[0]) * imgArray.shape[1] # x_center*W - bbox의 x센터
            y_center = float(data[0]['Point(x,y)'].split(',')[1]) * imgArray.shape[0] # y_center*H - bbox의 y센터

            y_width = float(data[0]['W']) # bbox의 w
            y_height = float(data[0]['H']) # bbox의 h

            coco_width = y_width * imgArray.shape[1] # bbox의 픽셀단위 w
            coco_height = y_height * imgArray.shape[0] # bbox의 픽셀단위 h
            print(coco_width, coco_height)

            start_x = x_center - (coco_width / 2) # start x좌표
            start_y = y_center - (coco_height / 2) # start y좌표
            
            end_x = x_center + (coco_width / 2) # end x좌표
            end_y = y_center + (coco_height / 2) # end y좌표

            print(start_x, start_y)
            
            # 시각화
            img = cv2.rectangle(imgArray, (int(start_x), int(start_y)), (int(end_x), int(end_y)), (0,255,0), 3).copy() # (이미지, start, end, color, thickness)
            # cv2.putText(image, bbox_mess, (c1[0], int(np.float32(c1[1] - 2))), cv2.FONT_HERSHEY_SIMPLEX, fontScale, (0, 0, 0), bbox_thick // 2, lineType=cv2.LINE_AA)
            plt.title(f'{j}, {img_shape}, {((start_x,start_y),(end_x, end_y))}')
            plt.imshow(img)
            count +=1        
                                
        # case 2 : properties
        else: 
            with open(f'./kfood_sy/{i}/{j}/label/crop_area.properties',mode='r',encoding='UTF8') as f:
                data = f.read()
                data_list = data.split('\n')[:-1] # '[Img_133_0012=4,96,322,445' , ... ]
            for bbox in data_list:
                if choice[:-4] in bbox:
                    xy = bbox.split('=')[1].split(',') # ['4','96','322','445']
                    print(xy)
                else:
                    continue
            img = cv2.rectangle(imgArray, (int(xy[0]), int(xy[1])), (int(xy[0])+int(xy[2]), int(xy[1])+int(xy[3])), (0,255,0), 3).copy() # (이미지, start, end, color, thickness)
            plt.title(f'{j}, {img_shape}, {((start_x,start_y),(end_x, end_y))}')
            plt.imshow(img)
            count +=1 
            
    plt.tight_layout()

output