#!/usr/bin/env python3
"""Erase colored pen (and, with --light, pencil) from a scanned page. Keep the black print and
(without --light) gray shading.

  python3 erase_ink.py filled.jpg blank.png              blue or red pen
  python3 erase_ink.py filled.jpg blank.png --light 130  pencil too: anything lighter than 130 of 255

A pixel with color (its highest and lowest RGB values more than 40 apart) is ink. It and a 2 px ring
around it become paper color, except dark pixels (print, and print under the ink). Black pen looks like
print, so this script cannot remove it. Needs: pip install numpy pillow

From https://brasspage.com/erase-handwriting/ (MIT License, Brasspage, 2026).
"""

import argparse

import numpy as np
from PIL import Image, ImageFilter


def erase(rgb, chroma=40, light=None):
    """rgb: H x W x 3 uint8 array. Returns a new array with colored ink (and light marks) set to paper."""
    a = rgb.astype(np.int16)
    mx, mn = a.max(2), a.min(2)
    paper = np.median(rgb.reshape(-1, 3)[::97], 0).astype(np.uint8)
    ink = Image.fromarray(((mx - mn) > chroma).astype(np.uint8) * 255)
    ring = np.asarray(ink.filter(ImageFilter.MaxFilter(5))) > 0
    # print, and print under ink, is darker than 110: pen ink alone is not
    gone = ring & (mx >= 110)
    if light is not None:
        gone |= np.asarray(Image.fromarray(rgb).convert("L")) > light
    out = rgb.copy()
    out[gone] = paper
    return out


def main():
    p = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    p.add_argument("src")
    p.add_argument("dst")
    p.add_argument(
        "--chroma",
        type=int,
        default=40,
        help="color spread that counts as ink (default 40)",
    )
    p.add_argument(
        "--light",
        type=int,
        help="also erase pixels lighter than this gray level, 0 to 255",
    )
    a = p.parse_args()
    rgb = np.asarray(Image.open(a.src).convert("RGB"))
    Image.fromarray(erase(rgb, a.chroma, a.light)).save(a.dst)


if __name__ == "__main__":
    main()
