Skip to content

Commit 3a847f6

Browse files
authored
fix: fix pad to square for some rectangular images (#421)
1 parent 7627d78 commit 3a847f6

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

fastembed/image/transform/functional.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Sized, Union, Optional
1+
from typing import Sized, Union
22

33
import numpy as np
44
from PIL import Image
@@ -127,18 +127,24 @@ def pil2ndarray(image: Union[Image.Image, np.ndarray]):
127127
def pad2square(
128128
image: Image.Image,
129129
size: int,
130-
fill_color: Optional[Union[str, int, tuple[int, ...]]] = None,
130+
fill_color: Union[str, int, tuple[int, ...]] = 0,
131131
) -> Image.Image:
132132
height, width = image.height, image.width
133133

134-
# if the size is larger than the new canvas
135-
if width > size or height > size:
134+
left, right = 0, width
135+
top, bottom = 0, height
136+
137+
crop_required = False
138+
if width > size:
136139
left = (width - size) // 2
137-
top = (height - size) // 2
138140
right = left + size
141+
crop_required = True
142+
143+
if height > size:
144+
top = (height - size) // 2
139145
bottom = top + size
140-
image = image.crop((left, top, right, bottom))
146+
crop_required = True
141147

142-
new_image = Image.new(mode="RGB", size=(size, size), color=fill_color or 0)
143-
new_image.paste(image)
148+
new_image = Image.new(mode="RGB", size=(size, size), color=fill_color)
149+
new_image.paste(image.crop((left, top, right, bottom)) if crop_required else image)
144150
return new_image

fastembed/text/text_embedding.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def __init__(
7878
return
7979

8080
raise ValueError(
81-
f"Model {model_name} is not supported in TextEmbedding."
81+
f"Model {model_name} is not supported in TextEmbedding. "
8282
"Please check the supported models using `TextEmbedding.list_supported_models()`"
8383
)
8484

0 commit comments

Comments
 (0)