in src/co_op_translator/utils/vision/image_utils.py [0:0]
def pad_text_image_to_target_aspect(text_img, target_aspect, alignment):
"""
Pad the text image to approach the target aspect ratio.
If the text image is too wide (current_aspect > target_aspect), vertical
padding is added. If it is too narrow, horizontal padding is added according
to the effective alignment.
"""
h, w = text_img.shape[:2]
current_aspect = w / h if h > 0 else 1
if abs(current_aspect - target_aspect) < 1e-2:
return text_img
if current_aspect > target_aspect:
# Text is too wide: add vertical padding.
desired_height = int(round(w / target_aspect))
pad_total = desired_height - h
pad_top = pad_total // 2
pad_bottom = pad_total - pad_top
padded = cv2.copyMakeBorder(
text_img, pad_top, pad_bottom, 0, 0, cv2.BORDER_CONSTANT, value=[0, 0, 0, 0]
)
else:
# Text is too narrow: add horizontal padding.
desired_width = int(round(h * target_aspect))
pad_total = desired_width - w
if alignment == "left":
pad_left = 0
pad_right = pad_total
elif alignment == "right":
pad_left = pad_total
pad_right = 0
else: # center
pad_left = pad_total // 2
pad_right = pad_total - pad_left
padded = cv2.copyMakeBorder(
text_img, 0, 0, pad_left, pad_right, cv2.BORDER_CONSTANT, value=[0, 0, 0, 0]
)
return padded