Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371383 unmodified lines1421431441451461471481491501511521531541551561571581591601611621631641651661671681692 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)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, 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])2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291303 unmodified lines1341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691702 unmodified linesimport mathimport osdef load_as_pil(filepath):"""Open the uploaded image from the given filepath as a PIL (RGBA).This is so we can feed a PIL image to the crop tool."""if not filepath:return Nonereturn Image.open(filepath).convert("RGBA")def bounding_box_crop(img: Image.Image, bbox):"""Given a bounding box (left, top, right, bottom),crop the PIL image and return the cropped image.This function is triggered by the user drawing a rectangle with 'tool="select"'."""if img is None or bbox is None:return img # If no selection made, return originalleft, top, right, bottom = bbox# Safety checkleft = max(0, left)top = max(0, top)right = min(img.width, right)bottom = min(img.height, bottom)cropped = img.crop((left, top, right, bottom))return croppeddef get_pixel_color_from_pil(cropped_img: Image.Image, evt: gr.SelectData):"""Eyedropper on the cropped image:1) We receive the (x, y) in the cropped image's coordinate space.2) Return that pixel color in #RRGGBB format."""if cropped_img is None:return Nonex, y = evt.indexif x < 0 or y < 0 or x >= cropped_img.width or y >= cropped_img.height:return Noner, g, b, *rest = cropped_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(original_filepath, cropped_img, chosen_hex, threshold):"""1) We use the original file's base name for final naming (PNG).2) On the cropped_img, any pixel within 'threshold' distance to chosen_hex => black; else transparent.3) Return the final processed image + downloadable file."""if not original_filepath or cropped_img is None:return None, None# Determine the final filenamebase_name = os.path.basename(original_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 RGBA for safe data manipulationcropped_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 blacknew_pixels.append((0, 0, 0, a))else:# Otherwise, fully 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 With Bounding Box, Then Eyedrop + Transparency\n""**Step 1**: Upload an image (keeping original filename).\n""**Step 2**: Drag a rectangle on the image to crop. (If no box drawn, the original is used.)\n""**Step 3**: Click on the cropped image to pick a color.\n""**Step 4**: Adjust threshold and click 'Apply' to make that color black, all else transparent.\n""**Step 5**: Download the PNG.")with gr.Row():with gr.Column():# (A) Upload with type="filepath" so we keep the original filenameoriginal_image = gr.Image(type="filepath",label="Upload Image (filename preserved)")# (B) A second component for bounding-box cropping:# - "tool='select'" lets user drag a bounding box# - We'll specify "type='pil'" so we can pass it to bounding_box_crop()image_for_crop = gr.Image(type="pil",tool="select",label="Drag to select a region to crop")# We'll store the cropped image for the next stepscropped_image = gr.Image(type="pil",label="Cropped Image (click to pick color)")with gr.Column():# Color picking + thresholdcolor_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")# 1) When user uploads an image (filepath), load it as a PIL for the bounding box tooldef load_image(filepath):return load_as_pil(filepath)original_image.change(fn=load_image,inputs=original_image,outputs=image_for_crop)# 2) Crop: user draws a box on image_for_crop => bounding_box_crop => cropped_imageimage_for_crop.select(fn=bounding_box_crop,inputs=[image_for_crop],outputs=[cropped_image])# 3) Eyedrop: user clicks on cropped_image => get_pixel_color_from_pil => color_pickercropped_image.select(fn=get_pixel_color_from_pil,inputs=cropped_image,outputs=color_picker)# 4) Apply transform => produce finalapply_button.click(fn=apply_transform,inputs=[original_image, cropped_image, color_picker, threshold_slider],outputs=[result_image, download_file])
app.py+110-109