Spaces:
Sleeping
Sleeping
Download make_transparent_aggressive.py from kcooley03/LiftLocaldemo: direct link, hf CLI and curl.
- Browser
- Download file 1.37 kB
-
https://huggingface.co/spaces/kcooley03/LiftLocaldemo/resolve/main/make_transparent_aggressive.py
- Command line
-
hf download hf://spaces/kcooley03/LiftLocaldemo/make_transparent_aggressive.py
-
curl -L -o make_transparent_aggressive.py https://huggingface.co/spaces/kcooley03/LiftLocaldemo/resolve/main/make_transparent_aggressive.py
1.37 kB
| from PIL import Image | |
| import os, math, shutil | |
| HERE = os.path.dirname(__file__) | |
| ORIG = os.path.join(HERE, 'liftlocall.png.bak') | |
| OUT = os.path.join(HERE, 'liftlocall.png') | |
| if not os.path.exists(ORIG): | |
| print('Backup original not found:', ORIG) | |
| raise SystemExit(2) | |
| print('Using backup source:', ORIG) | |
| im = Image.open(ORIG).convert('RGBA') | |
| px = im.load() | |
| width, height = im.size | |
| # sample corners for bg 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 = tuple(int(sum(c[i] for c in corner_samples)/len(corner_samples)) for i in range(3)) | |
| print('Estimated background color:', bg_color) | |
| # aggressive params | |
| TOLERANCE = 120.0 | |
| FEATHER = 40.0 | |
| changed = 0 | |
| for y in range(height): | |
| for x in range(width): | |
| r,g,b,a = px[x,y] | |
| # distance from bg | |
| dist = math.sqrt((r-bg_color[0])**2 + (g-bg_color[1])**2 + (b-bg_color[2])**2) | |
| if dist <= TOLERANCE: | |
| new_a = 0 | |
| elif dist <= TOLERANCE + FEATHER: | |
| 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 | |
| im.save(OUT) | |
| print(f'Wrote {OUT} (modified {changed} pixels)') | |
| print('Done') | |