Files
music-album-art-processor/cdcrop_resize.py
T
aarbit dbe6c44b68 Integrate resize+levels finishing into the review UI's accept flow
Accept now writes two files: OUTDIR/{cid}.png stays the untouched
full-resolution archival crop exactly as before, and a new
OUTDIR/finished/{cid}.jpg holds the resized (long-edge default 800) and
gamma/black-point-leveled derivative, saved at quality 60. Gamma/black
point/pre-blur are per-cover overridable in a new "Finish" panel (same
nudge-button + live-preview pattern as "Crop edges"), defaulting to the
global settings (gamma 1.2, long edge 800, JPEG quality 60) configurable
in Setup. cdcrop_resize.resize_image() was split out from resize_one() so
the UI can call it in-memory without file I/O, same as cdcrop_levels'
apply_levels() already allowed.
2026-11-11 23:38:07 -06:00

104 lines
4.2 KiB
Python

#!/usr/bin/env python3
"""
cdcrop_resize.py - resize cropped cover art to a web-sized PNG, the way you'd
do it by hand in Photoshop: resize down, optional unsharp mask.
Downscaling a halftone-printed scan by ~8-9x (a typical cover goes from a few
thousand px to an 800 px long edge) is exactly the regime where a plain
Lanczos resize aliases against the print's halftone pattern and shows up as
moire - which is why you've been pre-blurring by hand when you spot it.
Pillow's resize() only avoids that if you ask for it (reducing_gap >= 3.0
makes it box-reduce in whole-pixel steps before the final filtered resample,
instead of one unfiltered pass); this script always asks for it, so the
moire shouldn't show up in the first place. --pre-blur is kept as a manual
fallback for any image where that still isn't enough.
Usage:
python cdcrop_resize.py IN.png [IN2.png ...] -o OUTDIR
python cdcrop_resize.py INPUT_FOLDER -o OUTDIR
Options:
--long-edge PX target size of the longest edge (default 800)
--pre-blur SIGMA extra gaussian blur before resizing (default 0, off;
manual moire fallback if a cover still needs it)
--sharpen apply an unsharp mask after resizing
--sharpen-radius PX unsharp mask radius (default 1.0)
--sharpen-percent PCT unsharp mask strength (default 60)
--sharpen-threshold N unsharp mask threshold (default 2)
No DPI tag is written - the scan's DPI doesn't describe a 800 px derivative.
Requires: pip install pillow
"""
import argparse
import os
import sys
from PIL import Image, ImageFilter
RESIZE_GAP = 3.0 # >=3.0: Pillow's box-reduce pre-pass is indistinguishable from a fair resample
def resize_image(im, long_edge, pre_blur=0.0):
"""Core resize, usable on an in-memory image (no file I/O). Returns (image, was_resized)."""
w, h = im.size
scale = long_edge / max(w, h)
if scale >= 1.0:
return im, False
new_w, new_h = round(w * scale), round(h * scale)
if pre_blur > 0:
im = im.filter(ImageFilter.GaussianBlur(pre_blur))
im = im.resize((new_w, new_h), resample=Image.LANCZOS, reducing_gap=RESIZE_GAP)
return im, True
def sharpen_image(im, radius, percent, threshold):
return im.filter(ImageFilter.UnsharpMask(radius=radius, percent=percent, threshold=threshold))
def resize_one(path, outdir, long_edge, pre_blur, sharpen, sharpen_radius, sharpen_percent, sharpen_threshold):
im = Image.open(path)
mode = im.mode
w, h = im.size
out, resized = resize_image(im, long_edge, pre_blur)
if resized:
print(f" {os.path.basename(path)} {w}x{h} -> {out.size[0]}x{out.size[1]}"
+ (f" (pre-blur {pre_blur:g})" if pre_blur > 0 else ""))
else:
print(f" {os.path.basename(path)} {w}x{h} already <= {long_edge}px, copied as-is")
if sharpen:
out = sharpen_image(out, sharpen_radius, sharpen_percent, sharpen_threshold)
if out.mode != mode:
out = out.convert(mode)
out_path = os.path.join(outdir, os.path.basename(path))
out.save(out_path, format="PNG")
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("inputs", nargs="+", help="cropped PNGs, or a folder of them")
ap.add_argument("-o", "--outdir", required=True)
ap.add_argument("--long-edge", type=int, default=800)
ap.add_argument("--pre-blur", type=float, default=0.0)
ap.add_argument("--sharpen", action="store_true")
ap.add_argument("--sharpen-radius", type=float, default=1.0)
ap.add_argument("--sharpen-percent", type=int, default=60)
ap.add_argument("--sharpen-threshold", type=int, default=2)
a = ap.parse_args()
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:
resize_one(f, a.outdir, a.long_edge, a.pre_blur, a.sharpen,
a.sharpen_radius, a.sharpen_percent, a.sharpen_threshold)
print(f"\n{len(files)} cover(s) resized to {a.outdir}")
if __name__ == "__main__":
sys.exit(main())