The Meowgorithm Dotfiles, Collectors’ Edition
#!/usr/bin/env python3
"""Remove a solid background color from an image (e.g. terminal/markdown screenshots).
Uses exact alpha uncompositing (GIMP-style "Color to Alpha"): for each pixel it
inverts C = a*F + (1-a)*B, so anti-aliased text edges keep their true color and
get a fractional alpha instead of a dark halo.
Usage:
remove_bg.py INPUT OUTPUT [--bg R,G,B | --bg "#2d2c37"] [--corner x,y]
Background color defaults to the most common color among the four corners.
Output should be a format with alpha (PNG recommended).
"""
import argparse
import sys
try:
import numpy as np
from PIL import Image
except ImportError:
sys.exit(
"Missing dependencies. Install with: python3 -m pip install --user pillow numpy"
)
def parse_color(s):
s = s.strip()
if s.startswith("#"):
h = s.lstrip("#")
if len(h) == 3:
h = "".join(ch * 2 for ch in h)
if len(h) != 6:
raise argparse.ArgumentTypeError(f"Bad hex color: {s}")
return tuple(int(h[i : i + 2], 16) for i in (0, 2, 4))
parts = tuple(int(p) for p in s.split(","))
if len(parts) != 3:
raise argparse.ArgumentTypeError(f"Bad color: {s} (want R,G,B)")
return parts