franciszzj commited on
Commit
dd14542
1 Parent(s): e8ba64a

update resize_and_center

Browse files
Files changed (1) hide show
  1. 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, fill_color=(255, 255, 255)):
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
- Parameters:
10
- - image: PIL.Image object
11
- - target_width: Desired width of the final image
12
- - target_height: Desired height of the final image
13
- - fill_color: Background color used for padding
14
 
15
- Returns:
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
- # Create a new image with the desired size and fill color
22
- new_image = Image.new("RGB", (target_width, target_height), fill_color)
 
23
 
24
- # Calculate the position to center the resized image
25
- x_offset = (target_width - image.width) // 2
26
- y_offset = (target_height - image.height) // 2
27
 
28
- # Paste the resized image onto the new image with padding
29
- new_image.paste(image, (x_offset, y_offset))
30
 
31
- return new_image
 
 
 
 
 
 
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)