Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines3456678989101111121313151617181920212223242526272829141530313233343536373839401642434417181920212223242526512728293031323334355354553637383940414243574445466061626347484965666768697071505152535455565758737475596061626364798081826566676869707172737475767778798081828384848586878788888990919293949590969798999495969798991001011021031041051061071081091101041051111121131071141151091101111121131141151161161171181191201211221231181191201211221241251261271281291301311321331341351251261271361371383 unmodified lines1421431441451461471481401411421431441451461471481491501511521531541551561571581591601611491501511521531541551641561571581671591601611621631641651661671681692 unmodified linesimport mathimport os
def load_as_pil(filepath):def get_pixel_color_from_filepath(image_filepath, evt: gr.SelectData): """ 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. 1) Open the image (RGBA). 2) Retrieve the (x, y) pixel's color as #RRGGBB. """ if not filepath: if not image_filepath: return None return 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 original left, top, right, bottom = bbox # Safety check left = max(0, left) top = max(0, top) right = min(img.width, right) bottom = min(img.height, bottom)
img = Image.open(image_filepath).convert("RGBA")
cropped = img.crop((left, top, right, bottom)) return cropped
def 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 None x, y = evt.index if x < 0 or y < 0 or x >= cropped_img.width or y >= cropped_img.height: return None r, g, b, *rest = cropped_img.getpixel((x, y)) 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(original_filepath, cropped_img, chosen_hex, threshold):def apply_transform( image_filepath, color_hex1, color_hex2, threshold, use_color2, conversion_mode): """ 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. 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 original_filepath or cropped_img is None: if not image_filepath: return None, None
# Determine the final filename base_name = os.path.basename(original_filepath) # e.g. "photo.jpg" name_part, _ = os.path.splitext(base_name) # ("photo", ".jpg") out_name = name_part + ".png" img = Image.open(image_filepath).convert("RGBA") pixels = list(img.getdata())
# 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), ) 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), )
# Ensure RGBA for safe data manipulation cropped_img = cropped_img.convert("RGBA") pixels = list(cropped_img.getdata()) # 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: dist = rgb_distance(r, g, b, *chosen_rgb) if dist <= threshold: # Pixel matches chosen color => make black new_pixels.append((0, 0, 0, a)) # 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: # Otherwise, fully transparent # Outside threshold => transparent new_pixels.append((r, g, b, 0))
cropped_img.putdata(new_pixels) cropped_img.save(out_name, "PNG") 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 cropped_img, out_name return img, out_name
with 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." "# 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(): # (A) Upload with type="filepath" so we keep the original filename original_image = gr.Image( # Image & Eyedropper input_image = gr.Image( type="filepath", label="Upload Image (filename preserved)" label="Upload & Click to Pick Color 1" )
# (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" color1_picker = gr.ColorPicker( label="Color 1 (Eyedropper)", value="#ffffff" ) use_color2 = gr.Checkbox( label="Use Color 2?", value=False ) # We'll store the cropped image for the next steps cropped_image = gr.Image( type="pil", label="Cropped Image (click to pick color)" color2_picker = gr.ColorPicker( label="Color 2 (Optional)", value="#0000ff" )
# Conversion mode conversion_mode = gr.Radio( label="Conversion Mode", choices=["Black", "Grayscale"], value="Black" # default )
with gr.Column(): # Color picking + threshold 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")
with gr.Column(): 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 tool def 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_image image_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_picker cropped_image.select( fn=get_pixel_color_from_pil, inputs=cropped_image, outputs=color_picker # Eyedropper sets Color 1 input_image.select( fn=get_pixel_color_from_filepath, inputs=input_image, outputs=color1_picker )
# 4) Apply transform => produce final # Apply transform apply_button.click( fn=apply_transform, inputs=[original_image, cropped_image, color_picker, threshold_slider], inputs=[ input_image, color1_picker, color2_picker, threshold_slider, use_color2, conversion_mode ], outputs=[result_image, download_file] )
app.py+109-110