1. 라이브러리 import


import os
import shutil
from glob import glob
from PIL import Image

import tensorflow as tf
import numpy as np
from tqdm import tqdm

2. ret_img_path함수


def ret_img_path(all_paths, fname) :
    for path in all_paths :
        if fname in path:
            return path

3. cropping함수


def cropping(class_paths, main_class):
    # 결과물은 새로운 폴더에 저장
    # 클래스명을 활용해서 cropped_'class'폴더 생성
    save_dir_path = '../test/cropped_kfood/' + main_class +'/'
    
    if not os.path.exists(save_dir_path):
        os.makedirs(save_dir_path)
        print("main 디렉토리 생성 : ", save_dir_path)

    # crop_area path 저장
    print("crop_area 파일 수집중")
    for path in class_paths :
        if 'crop_area' in path :
            crop_path = path
            break

    # crop_area파일 읽기
        
    f = open(crop_path, 'r')
    data = f.read()
    f.close()

    crop_infos = data.split('\\n')
    cropped_fname = []

    # crop에 대한 정보가 있는 파일들은 crop을 하고,
    # 앞에서 새로 만든 cropped_classname 디렉터리에 저장
    print("crop 시작")
    for crop_info in tqdm(crop_infos) :

        fname = crop_info.split('=')[0]
        try :
            x, y, w, h = list(map(int, crop_info.split('=')[-1].split(',')))
        except :
            continue

        img_path = ret_img_path(class_paths, fname)

        try :
            image = Image.open(img_path)
            class_name = img_path.split('/')[-2]
        except :
            continue

#             print(class_name)
        image = image.convert("RGB")
        cropped_img = image.crop((x, y, x+w, y+h))
        img_save_path = save_dir_path + class_name + '/'
        if not os.path.exists(img_save_path) :
            os.makedirs(img_save_path)
            print("sub 디렉토리 생성 : ", img_save_path)
#             print(img_save_path + 'cropped_' + fname + '.jpg')
        cropped_img.save(img_save_path + 'cropped_' + fname + '.jpg')
        cropped_fname.append(fname)
    print("crop 끝")

    print("\\n\\ncrop을 하지 않은 이미지를 복사 중입니다.")
    print("잠시만 기다려 주세요")
    # crop이 필요없는 image들의 경우..
    # crop 경로에 똑같이 복사를 해준다
    for path in tqdm(class_paths):
        fname = path.split('/')[-1].split('.')[0]
        if fname not in cropped_fname and 'csv' not in path and 'properties' not in path:
            shutil.copy(path, img_save_path)

4. main