from PIL import Image import os import math """ Improved background removal: - Samples corner pixels to estimate the background color - Converts pixels close to that color (within tolerance) to transparent - Optional feathering (smooth alpha transition) to avoid hard edges Usage: run from the folder containing liftlocall.png. A backup is created at liftlocall.png.bak if not present. """ HERE = os.path.dirname(__file__) IMG = os.path.join(HERE, "liftlocall.png") BACKUP = IMG + ".bak" if not os.path.exists(IMG): print(f"Image not found: {IMG}") exit(2) # Backup original if no backup exists if not os.path.exists(BACKUP): import shutil shutil.copy2(IMG, BACKUP) print(f"Backed up original to {BACKUP}") else: print(f"Backup already exists at {BACKUP}") def avg_color(colors): """Average a list of (r,g,b) tuples""" n = len(colors) return tuple(int(sum(c[i] for c in colors) / n) for i in range(3)) def color_distance(c1, c2): return math.sqrt(sum((c1[i] - c2[i]) ** 2 for i in range(3))) im = Image.open(IMG).convert("RGBA") px = im.load() width, height = im.size # Sample corners to estimate background color corner_samples = [] for cx, cy in [(0, 0), (width - 1, 0), (0, height - 1), (width - 1, height - 1)]: r, g, b, a = px[cx, cy] corner_samples.append((r, g, b)) bg_color = avg_color(corner_samples) print(f"Estimated background color (from corners): {bg_color}") # Parameters (tweak if needed) TOLERANCE = 80.0 # color distance below which we consider pixel background FEATHER = 24.0 # smooth transition over this distance changed = 0 for y in range(height): for x in range(width): r, g, b, a = px[x, y] dist = color_distance((r, g, b), bg_color) if dist <= TOLERANCE: # fully transparent for close matches new_a = 0 elif dist <= TOLERANCE + FEATHER: # feather alpha proportionally frac = (dist - TOLERANCE) / FEATHER new_a = int(a * min(1.0, frac)) else: new_a = a if new_a != a: px[x, y] = (r, g, b, new_a) changed += 1 if changed == 0: print(f"No pixels changed (TOLERANCE={TOLERANCE}). Try increasing tolerance.)") else: im.save(IMG) print(f"Made {changed} pixels updated (alpha modified) and saved {IMG}") print("Done")