Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677781 unmodified line80818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691702 unmodified linesimport mathimport osdef upscale_image(img, zoom_factor):"""Upscale the image by zoom_factor using nearest-neighbor."""if img is None:return Nonew, h = img.size# Scalenew_w = int(w * zoom_factor)new_h = int(h * zoom_factor)return img.resize((new_w, new_h), Image.NEAREST)def pick_pixel_color(original_img, x, y):"""Get the pixel color (in #RRGGBB) from (x, y) in the original_img."""if original_img is None:return Noneif not (0 <= x < original_img.width and 0 <= y < original_img.height):return Noner, g, b, *rest = original_img.getpixel((x, y))return "#{:02x}{:02x}{:02x}".format(r, g, b)def get_zoomed_image_and_filename(image_filepath, zoom_factor):"""1) Open the original image (keeping the original filename).2) Return the upscaled image for display, plus the original PIL image(hidden output) so we don't lose it.3) Also return the base filename so we can preserve it later."""if not image_filepath:return None, None, None# Keep original filenamebase_name = os.path.basename(image_filepath)# Convert to RGBAorig_img = Image.open(image_filepath).convert("RGBA")zoomed = upscale_image(orig_img, zoom_factor)return zoomed, orig_img, base_namedef on_image_click(orig_img, zoom_factor, evt: gr.SelectData):"""Called when user clicks the upscaled image.We map (x, y) from the zoomed image back to the original image.Then pick that pixel’s color in hex."""if orig_img is None or evt is None:return Nonex_zoom, y_zoom = evt.index # (x, y) in zoomed coordinate space# Map back to the original coordsx_orig = int(x_zoom / zoom_factor)y_orig = int(y_zoom / zoom_factor)return pick_pixel_color(orig_img, x_orig, y_orig)def rgb_distance(r1, g1, b1, r2, g2, b2):return math.sqrt((r1 - r2)**2 + (g1 - g2)**2 + (b1 - b2)**2)def apply_transform(orig_img, chosen_hex, threshold, base_name):"""1) For all pixels in orig_img:- If within 'threshold' of chosen_hex, make it black (preserve alpha).- Else fully transparent.2) Save as PNG with same base name as upload.3) Return final PIL image + filename for download."""if orig_img is None or not base_name:return None, Noneimg = orig_img.copy()pixels = list(img.getdata())chosen_hex = chosen_hex.lstrip("#")chosen_rgb = (int(chosen_hex[0:2], 16),1 unmodified lineint(chosen_hex[4:6], 16),)new_pixels = []for (r, g, b, a) in pixels:dist = rgb_distance(r, g, b, *chosen_rgb)if dist <= threshold:# Pixel becomes blacknew_pixels.append((0, 0, 0, a))else:# Everything else => fully transparentnew_pixels.append((r, g, b, 0))img.putdata(new_pixels)out_name, _ = os.path.splitext(base_name)out_name += ".png"img.save(out_name, "PNG")return img, out_namewith gr.Blocks() as demo:gr.Markdown("# Zoomed Eyedropper Example\n""1. **Upload** an image (we keep the original filename).\n""2. Adjust the **Zoom** slider to enlarge for easier color picking.\n""3. **Click** on the zoomed image. We'll pick that pixel's color from the original image.\n""4. Click **Apply** to turn that color to black, making other pixels transparent.\n""5. **Download** the result as a PNG with the same base name.")with gr.Row():image_input = gr.Image(type="filepath", label="Upload Image")zoom_slider = gr.Slider(minimum=1, maximum=8, step=1,value=2, label="Zoom Factor")# We'll store the zoomed image in "zoomed_image" for display,# and the original PIL in "orig_image" hidden from the user,# plus we store the "base_filename" from the upload.zoomed_image = gr.Image(type="pil", label="Zoomed View")orig_image = gr.State()base_filename = gr.State()# We also have a color picker & threshold slider for the transformcolor_picker = gr.ColorPicker(label="Chosen Color", value="#ffffff")threshold_slider = gr.Slider(label="Threshold",minimum=0,maximum=255,value=40,step=1)# The final outputresult_image = gr.Image(type="pil", label="Result Preview")download_file = gr.File(label="Download PNG")# 1) Update Zoomed Image whenever user uploads or changes zoomdef update_zoom(image_filepath, zoom):return get_zoomed_image_and_filename(image_filepath, zoom)image_input.change(fn=update_zoom,inputs=[image_input, zoom_slider],outputs=[zoomed_image, orig_image, base_filename])zoom_slider.change(fn=update_zoom,inputs=[image_input, zoom_slider],outputs=[zoomed_image, orig_image, base_filename])# 2) Eyedropper: when user clicks on zoomed_image# we figure out color from original imagedef on_click(orig_img, zoom, evt):return on_image_click(orig_img, zoom, evt)zoomed_image.select(fn=on_click,inputs=[orig_image, zoom_slider],outputs=color_picker)# 3) Apply the color->black transformapply_button = gr.Button("Apply")apply_button.click(fn=apply_transform,inputs=[orig_image, color_picker, threshold_slider, base_filename],outputs=[result_image, download_file])2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546471 unmodified line4950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171182 unmodified linesimport mathimport osdef get_pixel_color_from_filepath(image_filepath, evt: gr.SelectData):"""1) Open the image (RGBA).2) Use the (x, y) click coordinates from evt to get that pixel's (R, G, B).3) Return the color as a hex string, e.g. '#RRGGBB'."""if not image_filepath:return None # No file to open yet# Open the image so we can read its pixelsimg = Image.open(image_filepath).convert("RGBA")# evt.index is (x, y) in 0-based coordinatesx, y = evt.indexif x < 0 or y < 0 or x >= img.width or y >= img.height:return None # Out of bounds (shouldn't happen)r, g, b, *rest = img.getpixel((x, y)) # Could be RGBA or RGBreturn "#{: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, chosen_hex, threshold):"""1) Open the original image in RGBA.2) Pixels that are within 'threshold' distance of 'chosen_hex' become BLACK (0,0,0) but keep alpha.3) All other pixels become fully transparent (alpha=0).4) Save the final as a PNG with the same base name as the uploaded file."""if not image_filepath:return None, None # No file to process# Open image as RGBAimg = Image.open(image_filepath).convert("RGBA")pixels = list(img.getdata())# Convert chosen_hex (#RRGGBB) to (R, G, B)chosen_hex = chosen_hex.lstrip("#")chosen_rgb = (int(chosen_hex[0:2], 16),1 unmodified lineint(chosen_hex[4:6], 16),)# Change chosen color to black, everything else -> transparentnew_pixels = []for (r, g, b, a) in pixels:dist = rgb_distance(r, g, b, *chosen_rgb)if dist <= threshold:# This pixel is close enough to the chosen color:# Make it black but preserve alphanew_pixels.append((0, 0, 0, a))else:# Make it fully transparentnew_pixels.append((r, g, b, 0))img.putdata(new_pixels)# Use the same base name as the original, but .pngbase_name = os.path.basename(image_filepath) # e.g. "photo.jpg"name_part, _ = os.path.splitext(base_name) # ("photo", ".jpg")output_filename = name_part + ".png" # => "photo.png"img.save(output_filename, "PNG")# Return: (preview Image, downloadable file)return img, output_filenamewith gr.Blocks() as demo:gr.Markdown("# Eyedropper to Make a Chosen Color Black\n""1. Upload an image.\n""2. Click on the image to pick a color (eyedropper).\n""3. Adjust threshold and click **Apply**.\n"" - Pixels matching your chosen color → **Black**.\n"" - All others → fully **transparent**.\n""4. Download the result (same base name as your upload, but .png).")with gr.Row():# We use type="filepath" to preserve the original filename.# Gradio v3.23+ supports .select() events even when type="filepath".input_image = gr.Image(type="filepath", label="Upload & Click to Pick Color")with gr.Column():color_picker = gr.ColorPicker(label="Eyedropper Color", value="#ffffff")threshold_slider = gr.Slider(label="Threshold",minimum=0,maximum=255,value=40,step=1)apply_button = gr.Button("Apply")result_image = gr.Image(type="pil", label="Result Preview")download_file = gr.File(label="Download PNG")# 1) Eyedropper step: when user clicks the image, we extract pixel colorinput_image.select(fn=get_pixel_color_from_filepath,inputs=input_image,outputs=color_picker)# 2) Processing step: user clicks "Apply" to transform the imageapply_button.click(fn=apply_transform,inputs=[input_image, color_picker, threshold_slider],outputs=[result_image, download_file])
app.py+65-117