Spaces:
Running
on
Zero
Running
on
Zero
franciszzj
commited on
Commit
•
dd14542
1
Parent(s):
e8ba64a
update resize_and_center
Browse files- utils/utils.py +22 -22
utils/utils.py
CHANGED
@@ -1,31 +1,31 @@
|
|
|
|
|
|
1 |
from PIL import Image
|
2 |
|
3 |
|
4 |
-
def resize_and_center(image, target_width, target_height
|
5 |
-
|
6 |
-
Resize the image to fit within (target_width, target_height) while maintaining aspect ratio,
|
7 |
-
and center it with padding to match the exact target size.
|
8 |
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
- fill_color: Background color used for padding
|
14 |
|
15 |
-
|
16 |
-
- A resized and centered PIL.Image object
|
17 |
-
"""
|
18 |
-
# Resize the image while maintaining the aspect ratio
|
19 |
-
image.thumbnail((target_width, target_height), Image.Resampling.LANCZOS)
|
20 |
|
21 |
-
|
22 |
-
|
|
|
23 |
|
24 |
-
|
25 |
-
|
26 |
-
y_offset = (target_height - image.height) // 2
|
27 |
|
28 |
-
|
29 |
-
|
30 |
|
31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
from PIL import Image
|
4 |
|
5 |
|
6 |
+
def resize_and_center(image, target_width, target_height):
|
7 |
+
img = np.array(image)
|
|
|
|
|
8 |
|
9 |
+
if img.shape[-1] == 4:
|
10 |
+
img = cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
|
11 |
+
elif len(img.shape) == 2 or img.shape[-1] == 1:
|
12 |
+
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
|
|
|
13 |
|
14 |
+
original_height, original_width = img.shape[:2]
|
|
|
|
|
|
|
|
|
15 |
|
16 |
+
scale = min(target_height / original_height, target_width / original_width)
|
17 |
+
new_height = int(original_height * scale)
|
18 |
+
new_width = int(original_width * scale)
|
19 |
|
20 |
+
resized_img = cv2.resize(img, (new_width, new_height),
|
21 |
+
interpolation=cv2.INTER_CUBIC)
|
|
|
22 |
|
23 |
+
padded_img = np.ones((target_height, target_width, 3),
|
24 |
+
dtype=np.uint8) * 255
|
25 |
|
26 |
+
top = (target_height - new_height) // 2
|
27 |
+
left = (target_width - new_width) // 2
|
28 |
+
|
29 |
+
padded_img[top:top + new_height, left:left + new_width] = resized_img
|
30 |
+
|
31 |
+
return Image.fromarray(padded_img)
|