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