Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines5678910113 unmodified lines151617181920214 unmodified lines2627282930313233343536373839404142434445464748491 unmodified line515253545556575859606162636465666768691 unmodified line717273747576772 unmodified lines808182838485868788899 unmodified lines9910010110210310410510610710814 unmodified lines1231241251261271281291301311324 unmodified linesdef get_pixel_color_from_filepath(image_filepath, evt: gr.SelectData):"""Eyedropper:1) Open the image (RGBA).2) Retrieve the (x, y) pixel's color as #RRGGBB."""3 unmodified linesimg = Image.open(image_filepath).convert("RGBA")x, y = evt.index# Safety checkif x < 0 or y < 0 or x >= img.width or y >= img.height:return None # Out of bounds4 unmodified lines"""Euclidean distance between two RGB colors."""return math.sqrt((r1 - r2)**2 + (g1 - g2)**2 + (b1 - b2)**2)def apply_transform_two_colors(image_filepath, color_hex1, color_hex2, threshold):"""Keep TWO colors:1) Convert image to RGBA.2) For each pixel:- If within threshold of color1 or color2, turn black (preserve alpha).- Else fully transparent.3) Save final as PNG with original base filename."""if not image_filepath:return None, None# Load imageimg = 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),1 unmodified lineint(hex_str[4:6], 16),)# Convert chosen colorsc1 = parse_hex(color_hex1)c2 = parse_hex(color_hex2)new_pixels = []for (r, g, b, a) in pixels:# Distance to color1dist1 = rgb_distance(r, g, b, *c1)# Distance to color2dist2 = rgb_distance(r, g, b, *c2)# If within threshold of either color => blackif dist1 <= threshold or dist2 <= threshold:new_pixels.append((0, 0, 0, a))else:new_pixels.append((r, g, b, 0))1 unmodified lineimg.putdata(new_pixels)# Preserve base name => .pngbase_name = os.path.basename(image_filepath) # e.g., "photo.jpg"name_part, _ = os.path.splitext(base_name)out_name = name_part + ".png"img.save(out_name, "PNG")2 unmodified lineswith gr.Blocks() as demo:gr.Markdown("# Keep Two Colors\n""1. **Upload** an image on the left.\n""2. **Click** on the image to eyedrop the first color.\n""3. **Pick** second color via color wheel/text (or see note below).\n""4. Adjust threshold, then **Apply**.\n""5. **Download** the PNG on the right.")9 unmodified lineslabel="Color 1 (Eyedropper)",value="#ffffff")color2_picker = gr.ColorPicker(label="Color 2",value="#0000ff")threshold_slider = gr.Slider(label="Threshold",minimum=0,14 unmodified linesoutputs=color1_picker)# When user clicks "Apply"apply_button.click(fn=apply_transform_two_colors,inputs=[input_image, color1_picker, color2_picker, threshold_slider],outputs=[result_image, download_file])4 unmodified lines56789103 unmodified lines1415161718194 unmodified lines242526272829303132333435363738394041424344451 unmodified line47484950515253545556575859606162636465666768697071721 unmodified line747576777879802 unmodified lines838485868788899091929 unmodified lines10210310410510610710810911011111211311411511611714 unmodified lines1321331341351361371381391401411421431441451461474 unmodified linesdef 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."""3 unmodified linesimg = Image.open(image_filepath).convert("RGBA")x, y = evt.indexif x < 0 or y < 0 or x >= img.width or y >= img.height:return None # Out of bounds4 unmodified lines"""Euclidean distance between two RGB colors."""return math.sqrt((r1 - r2)**2 + (g1 - g2)**2 + (b1 - b2)**2)def apply_transform_two_colors_optional(image_filepath, color_hex1, color_hex2, threshold, use_color2):"""1) Convert image to RGBA.2) Keep color1 always; keep color2 only if 'use_color2' is True.3) Any pixel close to these chosen color(s) => black (preserve alpha).Else => transparent.4) Save as .png with original base name."""if not image_filepath:return None, Noneimg = 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),1 unmodified lineint(hex_str[4:6], 16),)# Always parse color 1c1 = parse_hex(color_hex1)c2 = parse_hex(color_hex2) if use_color2 else Nonenew_pixels = []for (r, g, b, a) in pixels:make_black = False# Check color1dist1 = rgb_distance(r, g, b, *c1)if dist1 <= threshold:make_black = Trueelse:# Optionally check color2 if user wantsif c2 is not None:dist2 = rgb_distance(r, g, b, *c2)if dist2 <= threshold:make_black = Trueif make_black:new_pixels.append((0, 0, 0, a))else:new_pixels.append((r, g, b, 0))1 unmodified lineimg.putdata(new_pixels)# Preserve base name => .pngbase_name = os.path.basename(image_filepath)name_part, _ = os.path.splitext(base_name)out_name = name_part + ".png"img.save(out_name, "PNG")2 unmodified lineswith gr.Blocks() as demo:gr.Markdown("# Keep One or Two Colors\n""1. **Upload** an image on the left.\n""2. **Click** on the image to eyedrop the first color.\n""3. Optionally check 'Use Color 2' and pick a second color.\n""4. Adjust threshold, then **Apply**.\n""5. **Download** the PNG on the right.")9 unmodified lineslabel="Color 1 (Eyedropper)",value="#ffffff")use_color2 = gr.Checkbox(label="Use Color 2?",value=False)color2_picker = gr.ColorPicker(label="Color 2 (Optional)",value="#ff0000")threshold_slider = gr.Slider(label="Threshold",minimum=0,14 unmodified linesoutputs=color1_picker)# Apply transform: keep color1, optionally color2apply_button.click(fn=apply_transform_two_colors_optional,inputs=[input_image,color1_picker,color2_picker,threshold_slider,use_color2],outputs=[result_image, download_file])
app.py+40-25