#!/usr/bin/env python3 """Align an edited plate's figure bbox to the original plate's figure bbox. Image-edit models redraw the figure at their own scale/offset; the projection bake assumes the original framing, so misalignment = body sampling background (the v2 black-shard failure, 2026-07-18). Usage: align_plate.py original edited out""" import sys from PIL import Image def bbox(img, thresh=28): g = img.convert('RGB') px = g.load() w, h = g.size corner = px[2, 2] xs, ys = [], [] for y in range(0, h, 2): for x in range(0, w, 2): p = px[x, y] if sum(abs(p[i] - corner[i]) for i in range(3)) > thresh * 3: xs.append(x); ys.append(y) return min(xs), min(ys), max(xs), max(ys) orig, edit, out = sys.argv[1], sys.argv[2], sys.argv[3] o, e = Image.open(orig), Image.open(edit).convert('RGB') ob, eb = bbox(o), bbox(e) ow, oh = ob[2]-ob[0], ob[3]-ob[1] ew, eh = eb[2]-eb[0], eb[3]-eb[1] s = min(ow/ew, oh/eh) # uniform scale, height-fit fig = e.crop(eb).resize((round(ew*s), round(eh*s)), Image.LANCZOS) bg = e.getpixel((2, 2)) canvas = Image.new('RGB', o.size, bg) # anchor: match bbox centers horizontally, bottoms vertically (feet stay planted) cx = (ob[0]+ob[2])//2 - fig.width//2 canvas.paste(fig, (cx, ob[3]-fig.height)) canvas.save(out) print(f'orig bbox {ob} edit bbox {eb} scale {s:.3f} -> {out}')