Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines345678910111213141516171819202122232425262728293031323334353637381 unmodified line4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231243 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671682 unmodified linesimport mathimport osdef load_for_edit(filepath):"""Open the original image (filepath) as RGBAso the user can crop/rotate/etc. in the editor_image component."""if not filepath:return Nonereturn Image.open(filepath).convert("RGBA")def confirm_edits(edited_img):"""The user clicked "Confirm Crop/Edits."We simply pass the edited_img (already cropped) alongso that the next image component can do an eyedrop."""return edited_imgdef get_pixel_color(img: Image.Image, evt: gr.SelectData):"""Eyedropper: Given the cropped image and a click coordinate,return the color in #RRGGBB."""if img is None:return Nonex, y = evt.index# Safety checkif x < 0 or y < 0 or x >= img.width or y >= img.height:return Noner, g, b, *rest = img.getpixel((x, y))return "#{:02x}{:02x}{:02x}".format(r, g, b)1 unmodified line"""Euclidean distance between two RGB colors."""return math.sqrt((r1 - r2)**2 + (g1 - g2)**2 + (b1 - b2)**2)def apply_transform(image_filepath, cropped_img, chosen_hex, threshold):"""1) We use the original file's base name for the final PNG name.2) The user-supplied 'cropped_img' is where we do the eyedrop-based transparency.3) Any pixel within 'threshold' of chosen color => black, else transparent."""if not image_filepath or cropped_img is None:return None, None# Parse original filename for final namingbase_name = os.path.basename(image_filepath) # e.g. "photo.jpg"name_part, _ = os.path.splitext(base_name) # ("photo", ".jpg")out_name = name_part + ".png"# Convert the chosen hex (#RRGGBB) to (R, G, B)chosen_hex = chosen_hex.lstrip("#")chosen_rgb = (int(chosen_hex[0:2], 16),int(chosen_hex[2:4], 16),int(chosen_hex[4:6], 16),)# Ensure RGBAcropped_img = cropped_img.convert("RGBA")pixels = list(cropped_img.getdata())new_pixels = []for (r, g, b, a) in pixels:dist = rgb_distance(r, g, b, *chosen_rgb)if dist <= threshold:# Pixel matches chosen color => make black (0,0,0)new_pixels.append((0, 0, 0, a))else:# Otherwise transparentnew_pixels.append((r, g, b, 0))cropped_img.putdata(new_pixels)cropped_img.save(out_name, "PNG")return cropped_img, out_namewith gr.Blocks() as demo:gr.Markdown("# Crop, then Pick Color for Transparency\n""**Step 1**: Upload an image (preserving filename).\n""**Step 2**: Crop (or otherwise edit) the image using the built-in editor.\n""**Step 3**: Click 'Confirm Crop/Edits' to pass it along.\n""**Step 4**: Use eyedropper on the cropped image to pick a color.\n""**Step 5**: Adjust threshold and 'Apply' to make that color black, all else transparent.\n""**Step 6**: Download the resulting PNG with the same base name.")with gr.Row():# -- Left panelwith gr.Column():# 1) Upload image as FILEPATH, so we keep the original filenameoriginal_image = gr.Image(type="filepath",label="Upload Image (filename preserved)",)# 2) Editor for cropping (takes a PIL, returns a PIL)editor_image = gr.Image(type="pil",tool="editor",label="Crop/Rotate here, then confirm")confirm_button = gr.Button("Confirm Crop/Edits")# -- Right panelwith gr.Column():# This is the final cropped result that we can eyedropcropped_image = gr.Image(type="pil",label="Cropped Image (click to pick color)")color_picker = gr.ColorPicker(label="Chosen Color",value="#ffffff")threshold_slider = gr.Slider(label="Threshold",minimum=0,3 unmodified lines)apply_button = gr.Button("Apply")result_image = gr.Image(type="pil", label="Result Preview")download_file = gr.File(label="Download PNG")# Whenever user uploads an image, load it into the editordef load_editor_image(path):return load_for_edit(path)original_image.change(fn=load_editor_image,inputs=original_image,outputs=editor_image)# Clicking "Confirm Crop/Edits" => send final edited image to 'cropped_image'confirm_button.click(fn=confirm_edits,inputs=editor_image,outputs=cropped_image)# Eyedrop color from the cropped_imagecropped_image.select(fn=get_pixel_color,inputs=cropped_image,outputs=color_picker)# Final step: apply transform => color => black / rest => transparentapply_button.click(fn=apply_transform,inputs=[original_image, # for final filenamecropped_image, # the actual image to transformcolor_picker,threshold_slider],outputs=[result_image, download_file])2 unmodified lines3456789101112131415161718192021221 unmodified line242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371383 unmodified lines1421431441451461471481491501511521531541551561571581591601611621631641651661671682 unmodified linesimport mathimport osdef 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 Noneimg = 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 boundsr, g, b, *rest = img.getpixel((x, y))return "#{:02x}{:02x}{:02x}".format(r, g, b)1 unmodified line"""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, 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),int(hex_str[2:4], 16),int(hex_str[4:6], 16),)# Always parse color1c1 = parse_hex(color_hex1)c2 = parse_hex(color_hex2) if use_color2 else Nonenew_pixels = []for (r, g, b, a) in pixels:# Check distance to color1dist1 = rgb_distance(r, g, b, *c1)within_c1 = (dist1 <= threshold)# Check color2 if in usewithin_c2 = Falseif 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 colorif 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 => transparentnew_pixels.append((r, g, b, 0))img.putdata(new_pixels)# Output filename with same 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")return img, out_namewith gr.Blocks() as demo:gr.Markdown("# Keep One or Two Colors, Convert to Black or Grayscale\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.\n""5. Adjust threshold and **Apply**.\n""6. Download the PNG.")with gr.Row():with gr.Column():# Image & Eyedropperinput_image = gr.Image(type="filepath",label="Upload & Click to Pick Color 1")color1_picker = gr.ColorPicker(label="Color 1 (Eyedropper)",value="#ffffff")use_color2 = gr.Checkbox(label="Use Color 2?",value=False)color2_picker = gr.ColorPicker(label="Color 2 (Optional)",value="#0000ff")# Conversion modeconversion_mode = gr.Radio(label="Conversion Mode",choices=["Black", "Grayscale"],value="Black" # default)threshold_slider = gr.Slider(label="Threshold",minimum=0,3 unmodified lines)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 1input_image.select(fn=get_pixel_color_from_filepath,inputs=input_image,outputs=color1_picker)# Apply transformapply_button.click(fn=apply_transform,inputs=[input_image,color1_picker,color2_picker,threshold_slider,use_color2,conversion_mode],outputs=[result_image, download_file])
app.py+108-108