Spaces:
Sleeping
Sleeping
File size: 2,368 Bytes
4405280 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | 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")
|