Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243import gradio as grfrom PIL import Imagedef dark_pixels_only(input_image):"""Takes an image, converts to RGBA, and makes any pixel withANY component above 15 fully transparent."""# Convert image to RGBAimg = input_image.convert("RGBA")pixels = img.getdata()new_pixels = []for (r, g, b, a) in pixels:# Keep pixel's original alpha if R, G, B are <= 15.# Otherwise, make fully transparent.if r <= 15 and g <= 15 and b <= 15:new_pixels.append((r, g, b, a))else:new_pixels.append((r, g, b, 0))# Update pixelsimg.putdata(new_pixels)# Save to disk so we can give a file path to Gradioout_path = "processed.png"img.save(out_path)# Return a tuple: (preview_image, downloadable_file)return img, out_pathdemo = gr.Interface(fn=dark_pixels_only,inputs=gr.Image(type="pil"),outputs=[gr.Image(type="pil", label="Preview of Processed Image"),gr.File(label="Download Processed Image")],title="Make Non-Dark Pixels Transparent",description="Pixels with R,G,B ≤ 15 retain their alpha; everything else becomes transparent.")if __name__ == "__main__":12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152import osimport gradio as grfrom PIL import Imagedef dark_pixels_only(input_filepath):"""Takes an image file path, converts to RGBA,and makes pixels fully transparent if ANY component > 15.Returns a tuple of (PIL preview image, downloadable file path)."""# Open the original image as RGBAimg = Image.open(input_filepath).convert("RGBA")pixels = img.getdata()new_pixels = []for (r, g, b, a) in pixels:if r <= 15 and g <= 15 and b <= 15:new_pixels.append((r, g, b, a)) # keep original alphaelse:new_pixels.append((r, g, b, 0)) # fully transparentimg.putdata(new_pixels)# Derive a new filename based on the original name but use '.png'base_name = os.path.basename(input_filepath) # e.g., "my_photo.jpg"name_part, _ = os.path.splitext(base_name) # ("my_photo", ".jpg")output_filename = name_part + ".png" # "my_photo.png"# Save the processed image to diskimg.save(output_filename, "PNG")# Return (preview image, downloadable file)return img, output_filenamedemo = gr.Interface(fn=dark_pixels_only,# Use `type="filepath"` to retrieve the original filename in the functioninputs=gr.Image(type="filepath", label="Upload your Image"),outputs=[gr.Image(type="pil", label="Preview of Processed Image"),gr.File(label="Download Processed Image")],title="Make Non-Dark Pixels Transparent",description=("Any pixel with R, G, or B > 15 is made fully transparent. ""Pixels with R,G,B ≤ 15 retain their original alpha. ""The output file keeps the same base name as the uploaded file, but is saved as a PNG."))if __name__ == "__main__":
app.py+27-18