Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
import os | |
from PIL import Image | |
import numpy as np | |
def resize_and_pad(img, desired_size): | |
"""Resize an image and pad it to the desired size while maintaining the aspect ratio.""" | |
# Ensure image is in RGB | |
if img.mode != "RGB": | |
img = img.convert("RGB") | |
# Compute the new size to maintain aspect ratio | |
ratio = float(desired_size) / max(img.size) | |
new_size = tuple([int(x * ratio) for x in img.size]) | |
img = img.resize(new_size, Image.Resampling.LANCZOS) | |
# Create a new image with mean color padding | |
new_im = Image.new("RGB", (desired_size, desired_size)) | |
pixel_values = np.array(img) | |
mean_color = tuple(np.mean(np.mean(pixel_values, axis=0), axis=0).astype(int)) | |
new_im.paste(Image.new("RGB", new_im.size, mean_color), (0, 0)) | |
# Paste resized image onto the background | |
new_im.paste( | |
img, ((desired_size - new_size[0]) // 2, (desired_size - new_size[1]) // 2) | |
) | |
return new_im | |
def process_image(img, size): | |
processed_img = resize_and_pad(img, size) | |
return processed_img | |