Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101import gradio as grfrom PIL import Imageimport osdef process_image(image_path):"""1. Opens the uploaded file (by its temp filepath) 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 has a recommended output filename."""# Because we only have a temp filepath, this won't be the original user filename:input_filename = os.path.basename(image_path) # Something like 'tmpxyz.png'# Open imageimg = Image.open(image_path).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 temporary basename + suffix (not the original user filename)basename, _ = 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, # The recommended download filename"data": file_bytes}# Build the Gradio interfacedemo = gr.Interface(fn=process_image,inputs=gr.File(type="filepath"), # Accepts file input as a pathoutputs=[gr.Image(type="pil"), gr.File()] # Preview + downloadable file)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+36-85