Spaces:
Sleeping
Sleeping
File size: 1,443 Bytes
064aede 32b3901 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import numpy as np
from PIL import Image
def resize_image(image_array, max_size=1048576):
"""
Resizes a NumPy image array to a maximum total size of 1048576 pixels while preserving the aspect ratio.
Args:
image_array (numpy.ndarray): The input image array.
max_size (int): The maximum total size of the image in pixels (default is 1048576).
Returns:
numpy.ndarray: The resized image array.
"""
# Get the current size of the image
height, width, _ = image_array.shape
# Calculate the total size of the image
total_size = height * width
# If the image is already smaller than the max size, return the original image
if total_size <= max_size:
return image_array
# Calculate the aspect ratio
aspect_ratio = width / height
# Calculate the new dimensions while preserving the aspect ratio
if aspect_ratio > 1:
new_width = int(np.sqrt(max_size * aspect_ratio))
new_height = int(new_width / aspect_ratio)
else:
new_height = int(np.sqrt(max_size / aspect_ratio))
new_width = int(new_height * aspect_ratio)
# Resize the image using Pillow
image = Image.fromarray(image_array)
image = image.resize((new_width, new_height), resample=Image.BICUBIC)
# Convert the resized image back to a NumPy array
resized_image = np.array(image)
return resized_image |