Files
music-album-art-processor/cdcrop_levels.py
T
aarbit ab9aa05ac2 Add --black-point to cdcrop_levels.py
A per-cover escape hatch, same pattern as --pre-blur in cdcrop_resize.py:
off by default since the 12-cover fit only supports the flat gamma as a
general default, not a black-point push - turn it on per cover as needed.
2026-11-10 23:41:52 -06:00

93 lines
3.5 KiB
Python

#!/usr/bin/env python3
"""
cdcrop_levels.py - darken midtones with a flat gamma curve, approximating
your Photoshop Levels pass.
A fit against 12 of your finished covers (singled/manual/) showed your levels
moves aren't a black/white point stretch - these scans already use nearly the
full 0-255 range, so clipping endpoints only blows them out and made every
sample worse. What actually matches is a per-channel gamma darken of the
midtones; a single flat gamma (same value, all channels, every cover) got
close on every sample tested, so that's the starting default here. Covers
that need more than the default (darker art, heavier midtone pull) can be
re-run with a higher --gamma the same way --pre-blur works in
cdcrop_resize.py.
Some covers want their black point pushed deeper too (a separate move from
gamma - the Levels black slider, not the midtone one); that's left off by
default since it's a per-cover call, not something the 12-cover fit supports
as a general default. Turn it on with --black-point when a cover needs it.
Usage:
python cdcrop_levels.py IN.png [IN2.png ...] -o OUTDIR
python cdcrop_levels.py INPUT_FOLDER -o OUTDIR
Options:
--gamma G midtone darkening, out = 255*(in/255)**G (default 1.2; 1.0 = no change)
--black-point N clip N and below to black, stretch the rest, before gamma
(default 0, off; 0-254)
Requires: pip install pillow numpy
"""
import argparse
import os
import sys
import numpy as np
from PIL import Image
DEFAULT_GAMMA = 1.2
def apply_levels(im, gamma, black_point):
has_alpha = im.mode in ("RGBA", "LA")
rgb = im.convert("RGB") if im.mode != "RGB" else im
arr = np.asarray(rgb, dtype=np.float32)
if black_point > 0:
arr = np.clip(arr - black_point, 0, None) * (255.0 / (255 - black_point))
arr = 255.0 * np.clip(arr / 255.0, 0, 1) ** gamma
out = Image.fromarray(np.clip(arr, 0, 255).astype(np.uint8), mode="RGB")
if has_alpha:
out = out.convert("RGBA")
out.putalpha(im.getchannel("A"))
elif im.mode != "RGB":
out = out.convert(im.mode)
return out
def levels_one(path, outdir, gamma, black_point):
im = Image.open(path)
dpi = im.info.get("dpi")
out = apply_levels(im, gamma, black_point)
bp_note = f", black point {black_point}" if black_point > 0 else ""
print(f" {os.path.basename(path)} gamma {gamma:g}{bp_note}")
kw = {"dpi": tuple(round(float(d)) for d in dpi)} if dpi else {}
out.save(os.path.join(outdir, os.path.basename(path)), format="PNG", **kw)
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("inputs", nargs="+", help="cropped/resized PNGs, or a folder of them")
ap.add_argument("-o", "--outdir", required=True)
ap.add_argument("--gamma", type=float, default=DEFAULT_GAMMA)
ap.add_argument("--black-point", type=int, default=0)
a = ap.parse_args()
if not 0 <= a.black_point < 255:
ap.error("--black-point must be 0-254")
files = []
for p in a.inputs:
if os.path.isdir(p):
files += sorted(os.path.join(p, f) for f in os.listdir(p) if f.lower().endswith(".png"))
else:
files.append(p)
if not files:
ap.error("no PNG files found")
os.makedirs(a.outdir, exist_ok=True)
for f in files:
levels_one(f, a.outdir, a.gamma, a.black_point)
print(f"\n{len(files)} cover(s) leveled to {a.outdir}")
if __name__ == "__main__":
sys.exit(main())