File size: 2,364 Bytes
48b3884
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# app/image_utils.py

from PIL import Image, ImageDraw, ImageFont
import numpy as np

def add_watermark(image_array: np.ndarray, text: str, confidence: float) -> Image.Image:
    """
    Adds a translucent watermark to an image with the prediction result and confidence.

    Args:
        image_array: The input image as a NumPy array.
        text: The prediction text (e.g., "NORMAL" or "PNEUMONIA").
        confidence: The confidence score of the prediction.

    Returns:
        A PIL Image object with the watermark applied.
    """
    # Convert NumPy array to PIL Image
    image = Image.fromarray(image_array).convert("RGBA")
    
    # Create a transparent overlay for the text
    txt_overlay = Image.new("RGBA", image.size, (255, 255, 255, 0))
    draw = ImageDraw.Draw(txt_overlay)

    # Define watermark properties
    is_pneumonia = (text == "PNEUMONIA")
    box_color = (220, 53, 69, 180) if is_pneumonia else (25, 135, 84, 180) # Red for Pneumonia, Green for Normal
    text_color = (255, 255, 255, 255)
    
    # Define font (uses a default if a specific .ttf is not found)
    try:
        font_size = int(image.height / 8)
        font = ImageFont.truetype("arialbd.ttf", font_size)
    except IOError:
        print("Arial Bold font not found, using default. Watermark quality may be lower.")
        font_size = int(image.height / 8)
        font = ImageFont.load_default()

    # Define text and box position
    text_to_draw = f"{text}\n{confidence:.1%}"
    
    # Get text size
    try:
        # Use getbbox for modern Pillow versions
        _, _, text_width, text_height = draw.textbbox((0, 0), text_to_draw, font=font)
    except AttributeError:
        # Fallback for older Pillow versions
        text_width, text_height = draw.textsize(text_to_draw, font=font)
        
    position = (20, 20) # Top-left corner with some padding
    box_position = [
        position[0] - 10,
        position[1] - 10,
        position[0] + text_width + 10,
        position[1] + text_height + 10
    ]

    # Draw the semi-transparent rectangle and the text
    draw.rectangle(box_position, fill=box_color)
    draw.text(position, text_to_draw, font=font, fill=text_color)
    
    # Combine the overlay with the original image
    watermarked_image = Image.alpha_composite(image, txt_overlay)
    
    return watermarked_image.convert("RGB")