728x90
일반적으로 정사각형으로 만들면 화면비율이 깨짐
그런걸 방지하기 위해서 남는 부분은 다른 색으로 칠해버림

import matplotlib.pylab as plt
from PIL import Image
def expend2square(pil_img, background_color) : # 배경이미지 크기계산
width, heigth = pil_img.size
if width == heigth : # 이미 정사각형
return pil_img
elif width > heigth : # 너비가 > 높이인 경우
result = Image.new(pil_img.mode, (width, width), background_color)
result.paste(pil_img, (0, (width - heigth) // 2)) # x 좌표는 0, y 좌표는 이미지 중앙에 이미지 붙임
return result
else : # 높이가 > 너비인 경우
result = Image.new(pil_img.mode, (heigth, heigth), background_color)
result.paste(pil_img, ((heigth - width) //2,0)) # x 좌표는 이미지 중앙, y 좌표는 0 에 이미지 붙임
return result
def resize_with_padding(pil_img, new_size, background_color) : # 남는부분에 색칠하기
img = expend2square(pil_img, background_color)
img = img.resize((new_size[0], new_size[1]), Image.ANTIALIAS)
return img
img = Image.open("./image01.jpeg")
img_new = resize_with_padding(img, (300,300), (0,0,255)) # 300, 300 : 사진 크기 # 0,0,255 : RGB
plt.imshow(img)
plt.show()
plt.imshow(img_new)
plt.show()
728x90
'AI > [Preprocessing]' 카테고리의 다른 글
[전처리] 사진 여러장처럼 보이게만들기(Augmentation) (0) | 2023.06.16 |
---|---|
[전처리] 가져온 사진 정보 받기 (feat, xml) (1) | 2023.06.15 |
[전처리] 가져온 사진 정보 받기 (feat, json) (0) | 2023.06.14 |
[전처리] 폴더에 있는 사진 가져오기 (0) | 2023.06.14 |
[전처리] 범주형 데이터 전처리 (0) | 2023.06.06 |