Spaces:
Sleeping

File size: 5,014 Bytes
324c2a9
 
20d55e5
2326b8f
324c2a9
8e7bbf3
324c2a9
8e7bbf3
 
eb96502
8e7bbf3
f3e4f4f
2326b8f
8e7bbf3
 
2022045
8e7bbf3
 
 
 
c95a487
b023b04
0128ef2
c95a487
2326b8f
20d55e5
8e7bbf3
 
 
 
 
 
 
 
20d55e5
8e7bbf3
 
 
 
 
 
 
20d55e5
8e7bbf3
f3e4f4f
2326b8f
8e7bbf3
 
93e4689
8e7bbf3
 
 
 
 
 
 
 
07536d2
8e7bbf3
 
 
2326b8f
b023b04
20d55e5
8e7bbf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b023b04
8e7bbf3
b42cd5e
2326b8f
8e7bbf3
 
 
 
 
 
 
2022045
8e7bbf3
20d55e5
0128ef2
 
43398ba
8e7bbf3
 
 
43398ba
8e7bbf3
 
0128ef2
2326b8f
0128ef2
c95a487
8e7bbf3
 
f3e4f4f
8e7bbf3
07536d2
8e7bbf3
 
dc427a8
8e7bbf3
 
 
 
a840f7f
8e7bbf3
 
dc427a8
8e7bbf3
 
 
 
 
 
 
93e4689
07536d2
c95a487
 
 
 
 
 
 
 
2326b8f
8e7bbf3
07536d2
 
 
8e7bbf3
 
 
 
 
2326b8f
 
8e7bbf3
0128ef2
f061306
8e7bbf3
 
 
 
 
 
 
 
2326b8f
20d55e5
324c2a9
f3e4f4f
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import gradio as gr
from PIL import Image
import math
import os

def get_pixel_color_from_filepath(image_filepath, evt: gr.SelectData):
    """
    1) Open the image (RGBA).
    2) Retrieve the (x, y) pixel's color as #RRGGBB.
    """
    if not image_filepath:
        return None

    img = Image.open(image_filepath).convert("RGBA")

    x, y = evt.index
    if x < 0 or y < 0 or x >= img.width or y >= img.height:
        return None  # Out of bounds

    r, g, b, *rest = img.getpixel((x, y))
    return "#{:02x}{:02x}{:02x}".format(r, g, b)

def rgb_distance(r1, g1, b1, r2, g2, b2):
    """Euclidean distance between two RGB colors."""
    return math.sqrt((r1 - r2)**2 + (g1 - g2)**2 + (b1 - b2)**2)

def apply_transform(
    image_filepath, 
    color_hex1, 
    color_hex2, 
    threshold, 
    use_color2, 
    conversion_mode
):
    """
    1) Convert image to RGBA.
    2) Keep color1 always; keep color2 only if 'use_color2' is checked.
    3) For pixels within threshold of these color(s):
         - if conversion_mode == 'Black', set (r,g,b) -> (0,0,0).
         - if conversion_mode == 'Grayscale', compute grayscale of original pixel.
       All other pixels => fully transparent.
    4) Save .png with original base name.
    """
    if not image_filepath:
        return None, None

    img = Image.open(image_filepath).convert("RGBA")
    pixels = list(img.getdata())

    def parse_hex(hex_str):
        """Parse '#RRGGBB' => (R, G, B)."""
        hex_str = hex_str.lstrip("#")
        return (
            int(hex_str[0:2], 16),
            int(hex_str[2:4], 16),
            int(hex_str[4:6], 16),
        )

    # Always parse color1
    c1 = parse_hex(color_hex1)
    c2 = parse_hex(color_hex2) if use_color2 else None

    new_pixels = []
    for (r, g, b, a) in pixels:
        # Check distance to color1
        dist1 = rgb_distance(r, g, b, *c1)
        within_c1 = (dist1 <= threshold)

        # Check color2 if in use
        within_c2 = False
        if c2 is not None:
            dist2 = rgb_distance(r, g, b, *c2)
            within_c2 = (dist2 <= threshold)

        if within_c1 or within_c2:
            # Pixel is within threshold of at least one chosen color
            if conversion_mode == "Black":
                new_pixels.append((0, 0, 0, a))
            else:
                # Grayscale
                # Simple average approach: gray = round((r + g + b)/3)
                gray = round((r + g + b) / 3)
                new_pixels.append((gray, gray, gray, a))
        else:
            # Outside threshold => transparent
            new_pixels.append((r, g, b, 0))

    img.putdata(new_pixels)

    # Output filename with same base name => .png
    base_name = os.path.basename(image_filepath)
    name_part, _ = os.path.splitext(base_name)
    out_name = name_part + ".png"
    img.save(out_name, "PNG")

    return img, out_name

with gr.Blocks() as demo:
    gr.Markdown(
        "# Image Overlay Processing\n"
        "1. **Upload** an image.\n"
        "2. **Click** on the image to eyedrop Color 1.\n"
        "3. Optionally check 'Use Color 2' and pick a second color.\n"
        "4. Choose **Black** or **Grayscale** conversion for selected colors.\n"
        "5. Adjust threshold and **Apply**.\n"
        "6. Download the PNG."
    )

    with gr.Row():
        with gr.Column():
            # Image & Eyedropper
            input_image = gr.Image(
                type="filepath", 
                label="Upload & Click to Pick Color 1"
            )
            color1_picker = gr.ColorPicker(
                label="Color 1 (Eyedropper)",
                value="#000000"
            )
            use_color2 = gr.Checkbox(
                label="Use Color 2?",
                value=False
            )
            color2_picker = gr.ColorPicker(
                label="Color 2 (Optional)",
                value="#000000"
            )

            # Conversion mode
            conversion_mode = gr.Radio(
                label="Conversion Mode",
                choices=["Black", "Grayscale"],
                value="Black"  # default
            )

            threshold_slider = gr.Slider(
                label="Threshold",
                minimum=0,
                maximum=255,
                value=40,
                step=1
            )
            apply_button = gr.Button("Apply")

        with gr.Column():
            result_image = gr.Image(type="pil", label="Result Preview")
            download_file = gr.File(label="Download PNG")

    # Eyedropper sets Color 1
    input_image.select(
        fn=get_pixel_color_from_filepath,
        inputs=input_image,
        outputs=color1_picker
    )

    # Apply transform
    apply_button.click(
        fn=apply_transform,
        inputs=[
            input_image, 
            color1_picker, 
            color2_picker, 
            threshold_slider, 
            use_color2,
            conversion_mode
        ],
        outputs=[result_image, download_file]
    )

demo.launch()