Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import 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__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import gradio as grfrom PIL import Imageimport osdef process_image(image_file):"""1. Opens the uploaded file as a PIL image in RGBA.2. Checks if black pixels > 70%.3. Depending on black_ratio:- CODE 1: Invert, then make white transparent, and turn remaining pixels black- CODE 2: Keep near-black pixels, make others transparent4. Returns both a preview (PIL.Image) and a dictionary for direct downloadthat preserves a correct output filename."""# Extract the original filename (e.g., "picture.png")input_filename = os.path.basename(image_file.name)# Open imageimg = Image.open(image_file.name).convert("RGBA")pixels = list(img.getdata())total_pixels = len(pixels)# Count black pixelsblack_count = sum(1 for (r, g, b, a) in pixels if (r, g, b) == (0, 0, 0))black_ratio = black_count / total_pixels if total_pixels else 0# --------------------------------------# CODE 1: If background is predominantly black# --------------------------------------if black_ratio > 0.7:inverted_pixels = []for (r, g, b, a) in pixels:inverted_pixels.append((255 - r, 255 - g, 255 - b, a))img.putdata(inverted_pixels)# Refresh pixel datapixels = list(img.getdata())white_transparent_pixels = []for (r, g, b, a) in pixels:if (r, g, b) == (255, 255, 255):white_transparent_pixels.append((r, g, b, 0)) # Make white transparentelse:white_transparent_pixels.append((r, g, b, a))img.putdata(white_transparent_pixels)# Refresh pixel datapixels = list(img.getdata())blackened_pixels = []for (r, g, b, a) in pixels:if a == 0:blackened_pixels.append((r, g, b, a)) # Keep transparent as iselse:blackened_pixels.append((0, 0, 0, a)) # Make all else blackimg.putdata(blackened_pixels)# Use the original basename + new suffixbasename, _ = os.path.splitext(input_filename)output_filename = basename + "_transparent_black.png"# --------------------------------------# CODE 2: Background is NOT predominantly black# (Assume it's more white than black)# --------------------------------------else: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 near-blackelse:new_pixels.append((r, g, b, 0)) # Make others transparentimg.putdata(new_pixels)basename, _ = os.path.splitext(input_filename)output_filename = basename + "_near_black_only.png"# Save the processed image to a temp locationtemp_output_path = f"/tmp/{output_filename}"img.save(temp_output_path, "PNG")# Return two things:# 1) A PIL image for preview# 2) A dict containing name & data for the downloadable filewith open(temp_output_path, "rb") as f:file_bytes = f.read()return img, {"name": output_filename, # Ensures the correct name in download"data": file_bytes}# Build the Gradio interfacedemo = gr.Interface(fn=process_image,inputs=gr.File(type="file"), # Accepts file inputoutputs=[gr.Image(type="pil"), gr.File()] # Preview + downloadable file)# When running on Hugging Face Spaces, "demo.launch()" is enough.if __name__ == "__main__":demo.launch()
app.py+86-36