Image-Resize / test_bbox_thres.py
Zeph27's picture
position padding logic
3f3fff8
from PIL import Image, ImageDraw
def draw_bounding_box_with_threshold(input_path, output_path, threshold=0):
# Open the image and convert to RGBA
image = Image.open(input_path).convert("RGBA")
# Get the bounding box of the non-blank area with threshold
bbox = get_bounding_box_with_threshold(image, threshold)
if bbox:
# Create a copy of the image to draw on
draw_image = image.copy()
draw = ImageDraw.Draw(draw_image)
# Draw the bounding box
draw.rectangle(bbox, outline="red", width=3)
# Save the image with the bounding box
draw_image.save(output_path)
print(f"Processed image: Bounding box {bbox}")
else:
print("No non-blank area found in the image")
def get_bounding_box_with_threshold(image, threshold):
width, height = image.size
left, top, right, bottom = width, height, 0, 0
for y in range(height):
for x in range(width):
r, g, b, a = image.getpixel((x, y))
if a > threshold:
left = min(left, x)
top = min(top, y)
right = max(right, x)
bottom = max(bottom, y)
if left < right and top < bottom:
return (left, top, right, bottom)
else:
return None
# Example usage
input_image = "bria_output/1000485417_03.png"
output_image = "bbox_image_thres.png"
draw_bounding_box_with_threshold(input_image, output_image, threshold=10)