File size: 1,490 Bytes
3f3fff8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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)