Spaces:
Build error
Build error
Commit ·
dd14542
1
Parent(s): e8ba64a
update resize_and_center
Browse files12345678910111213141516171819202122232425262728293031from PIL import Imagedef resize_and_center(image, target_width, target_height, fill_color=(255, 255, 255)):"""Resize the image to fit within (target_width, target_height) while maintaining aspect ratio,and center it with padding to match the exact target size.Parameters:- image: PIL.Image object- target_width: Desired width of the final image- target_height: Desired height of the final image- fill_color: Background color used for paddingReturns:- A resized and centered PIL.Image object"""# Resize the image while maintaining the aspect ratioimage.thumbnail((target_width, target_height), Image.Resampling.LANCZOS)# Create a new image with the desired size and fill colornew_image = Image.new("RGB", (target_width, target_height), fill_color)# Calculate the position to center the resized imagex_offset = (target_width - image.width) // 2y_offset = (target_height - image.height) // 2# Paste the resized image onto the new image with paddingnew_image.paste(image, (x_offset, y_offset))return new_image12345678910111213141516171819202122232425262728293031import cv2import numpy as npfrom PIL import Imagedef resize_and_center(image, target_width, target_height):img = np.array(image)if img.shape[-1] == 4:img = cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)elif len(img.shape) == 2 or img.shape[-1] == 1:img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)original_height, original_width = img.shape[:2]scale = min(target_height / original_height, target_width / original_width)new_height = int(original_height * scale)new_width = int(original_width * scale)resized_img = cv2.resize(img, (new_width, new_height),interpolation=cv2.INTER_CUBIC)padded_img = np.ones((target_height, target_width, 3),dtype=np.uint8) * 255top = (target_height - new_height) // 2left = (target_width - new_width) // 2padded_img[top:top + new_height, left:left + new_width] = resized_imgreturn Image.fromarray(padded_img)
utils/utils.py+22-22