in src/co_op_translator/utils/vision/image_utils.py [0:0]
def warp_image_to_bounding_box(text_img_array, bounding_box, image_width, image_height):
"""
Apply a perspective warp to a text image so it fits a (possibly rotated)
bounding box. The text image is first resized to the rectangle defined by
the bounding box geometry, then warped.
"""
pts = np.array(bounding_box, dtype=np.float32).reshape(4, 2)
# Compute destination width and height.
widthA = np.linalg.norm(pts[0] - pts[1])
widthB = np.linalg.norm(pts[2] - pts[3])
maxWidth = max(int(widthA), int(widthB))
heightA = np.linalg.norm(pts[0] - pts[3])
heightB = np.linalg.norm(pts[1] - pts[2])
maxHeight = max(int(heightA), int(heightB))
src_pts = np.float32([[0, 0], [maxWidth, 0], [maxWidth, maxHeight], [0, maxHeight]])
# Resize the padded text image to the computed rectangle.
resized_text = cv2.resize(text_img_array, (maxWidth, maxHeight))
matrix = cv2.getPerspectiveTransform(src_pts, pts)
warped = cv2.warpPerspective(
resized_text, matrix, (image_width, image_height), flags=cv2.INTER_LINEAR
)
return warped