INNER CODE UNIT · Python
trim_whitespace
changyeyu/LLM-RL-Visualized · src/clip_images.py:5
def trim_whitespace(input_path, output_path, padding=10):
"""
Opens an image, trims the whitespace by comparing with a white background,
adds the specified padding to the cropped region, and saves the result.
"""
im = Image.open(input_path)
width, height = im.size
# Create a white background image with the same size
bg = Image.new(im.mode, im.size, (255, 255, 255))
diff = ImageChops.difference(im, bg)
# Get the bounding box of the non-white region
bbox = diff.getbbox()
if bbox:
left = max(bbox[0] - padding, 0)
upper = max(bbox[1] - padding, 0)
right = min(bbox[2] + padding, width)