본문 바로가기
반치용/문제해결(trouble shooting)

이미지 사이즈 일괄 변경 및 자르기

by  반  2020. 4. 2.

CNN학습용 데이터 만들 때, 사이즈가 다른 파일을 통일 시키고 원하는 부분만 사용하기 위한 코드입니다.

import os
from PIL import Image

# image resize & cutter
# resize parameter
re_width = 640
re_height = 480
# cutter parameter
crop_left = 205
crop_top = 92
crop_right = 545
crop_bottom = 390

for root, dirs, files in os.walk('./'):
    for idx, file in enumerate(files):
        fname, ext = os.path.splitext(file)
        if ext in ['.jpg','.png','.gif']:
            im = Image.open(file)
            width, height = im.size
            resized_im = im.resize((re_width,re_height))
            crop_image = resized_im.crop((crop_left, crop_top, crop_right, crop_bottom)) #좌상우하
            crop_image = crop_image.convert('RGB')
            crop_image.save('img_edited' + str(idx) + '.jpg')  

댓글