본문 바로가기
이미지/crop하기

파이썬에서 이미지 비율 유지하며 자르기 (512x512 pixel로)

by 만다린망고 2023. 11. 14.
반응형

이미지에서 가로와 세로 중 작은 쪽을 기준으로 512xN 형태로 변형합니다. aspect ratio 를 유지해야 하기 때문에 N이 얼마가 될지는 이미지에 따라 달라집니다. 변형한 뒤에 이미지의 중앙을 기준으로 512x512로 잘라냅니다. 코드는 아래와 같습니다. 

# 이미지 열기
img = Image.open(input_image_path)

# 이미지의 가로와 세로 크기 얻기
width, height = img.size

# 이미지의 가로와 세로 중에서 작은 쪽을 기준으로 512로 크기 조절하기
min_dimension = min(width, height)
ratio = 512 / min_dimension
new_width = int(width * ratio)
new_height = int(height * ratio)
resized_img = img.resize((new_width, new_height), Image.ANTIALIAS)

# 크기 조절된 이미지의 가로와 세로 크기 얻기
width, height = resized_img.size

# 중앙을 기준으로 512x512로 이미지 자르기
left = (width - 512) // 2
top = (height - 512) // 2
right = (width + 512) // 2
bottom = (height + 512) // 2
cropped_img = resized_img.crop((left, top, right, bottom))

# 자른 이미지 저장
output_image_path = "output_image_512x512.PNG"
cropped_img.save(output_image_path)

 

사용한 이미지는 아래와 같습니다. 

 

sample1.PNG
0.10MB

반응형

댓글