Cotton code
151 lines · 7.3 KB · PythonRaw
#!/usr/bin/env python3"""Test vectors for the face crop and alignment the Rust core takes over from the phones (coordinator, 27 Nov).    python3 scripts/albums-align-vectors.py --out assets/design/albums/alignWrites vectors.json and, per case, the source picture and the expected crop as PNG (lossless RGB). Nothing here is aperson: the pictures are drawn from numbers (gradients, rings and five dots), so the vectors carry no licence.THE CONTRACT the vectors pin (assets/design/albums/align/README.md says it in words):  input   an RGB picture (8-bit, row by row from the top) and five points in PIXEL-INDEX coordinates: the centre of the          top-left pixel is (0, 0), x to the right, y down. Order: the eye on the picture's left, the other eye, the nose          tip, the mouth corner on the left, the other corner. (Vision's `pointsInImageCoordinates` are continuous,          pixel centres at i + 0.5: the phone subtracts 0.5 before calling.)  model   the similarity transform (scale, rotation, translation; no reflection, no shear) that best maps the five          points onto ArcFace's template for 112x112 (least squares, Umeyama 1991 without reflection):              dst = [[a, -b], [b, a]] . src + [tx, ty]  output  112x112 RGB: output pixel (u, v), integers, takes the source at M^-1 . (u, v) with bilinear interpolation over          the four nearest pixel centres; a neighbour outside the picture counts as black (0, 0, 0). Each channel is          rounded to the nearest integer (halves away from zero) and clamped to 0..255.  refuse  when the five points have no spread (all the same point), answer an error, never a crop.Tolerance for an implementation: a, b, tx, ty within 1e-4 of the vectors; every crop byte within 1 of the vectors."""import argparseimport hashlibimport jsonfrom pathlib import Pathimport numpy as npfrom PIL import ImageTEMPLATE = np.array([    [38.2946, 51.6963],    [73.5318, 51.5014],    [56.0252, 71.7366],    [41.5493, 92.3655],    [70.7299, 92.2041],], dtype=np.float64)SIDE = 112def similarity(src, dst):    """Least-squares similarity src -> dst (Umeyama without reflection): (a, b, tx, ty)."""    ms, md = src.mean(0), dst.mean(0)    s, d = src - ms, dst - md    norm = (s ** 2).sum()    if norm <= 1e-12:        raise ValueError("the points have no spread")    a = (s[:, 0] * d[:, 0] + s[:, 1] * d[:, 1]).sum() / norm    b = (s[:, 0] * d[:, 1] - s[:, 1] * d[:, 0]).sum() / norm    tx = md[0] - (a * ms[0] - b * ms[1])    ty = md[1] - (b * ms[0] + a * ms[1])    return a, b, tx, tydef crop(img, a, b, tx, ty):    """The contract's bilinear warp, exactly."""    h, w, _ = img.shape    det = a * a + b * b    v, u = np.mgrid[0:SIDE, 0:SIDE].astype(np.float64)    # Inverse of [[a,-b],[b,a]]: [[a,b],[-b,a]] / det.    x = (a * (u - tx) + b * (v - ty)) / det    y = (-b * (u - tx) + a * (v - ty)) / det    x0, y0 = np.floor(x).astype(int), np.floor(y).astype(int)    fx, fy = x - x0, y - y0    padded = np.zeros((h + 2, w + 2, 3), dtype=np.float64)    padded[1:-1, 1:-1] = img    def at(yy, xx):        yy = np.clip(yy + 1, 0, h + 1)        xx = np.clip(xx + 1, 0, w + 1)        return padded[yy, xx]    out = (at(y0, x0) * ((1 - fx) * (1 - fy))[..., None] + at(y0, x0 + 1) * (fx * (1 - fy))[..., None]           + at(y0 + 1, x0) * ((1 - fx) * fy)[..., None] + at(y0 + 1, x0 + 1) * (fx * fy)[..., None])    # Far outside (more than one pixel), clip above would reuse the black border: still black. Round halves away from 0.    out = np.floor(out + 0.5)    return np.clip(out, 0, 255).astype(np.uint8)def picture(w, h, points, seed):    """Gradients, rings and a dot at each point: a crop shows at a glance whether the dots reached the template."""    rng = np.random.default_rng(seed)    y, x = np.mgrid[0:h, 0:w].astype(np.float64)    r = 128 + 100 * np.sin(x / (7 + 5 * rng.random())) * np.cos(y / 11)    g = 255 * x / max(1, w - 1)    bl = 255 * y / max(1, h - 1)    img = np.stack([r, g, bl], -1)    cx, cy = points.mean(0)    rings = (np.hypot(x - cx, y - cy) // 6) % 2 == 0    img[rings] *= 0.8    for px, py in points:        img[np.hypot(x - px, y - py) <= 2.5] = (255, 255, 255)    return np.clip(img.round(), 0, 255).astype(np.uint8)def placed(scale, degrees, centre, jitter=0.0, seed=0):    """The template moved into a picture: scaled, turned and placed, with optional jitter on each point."""    t = np.radians(degrees)    rot = np.array([[np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)]])    pts = (TEMPLATE - TEMPLATE.mean(0)) @ rot.T * scale + np.asarray(centre)    if jitter:        pts = pts + np.random.default_rng(seed).normal(0, jitter, pts.shape)    return ptsCASES = [    # name, picture size, points, what it tests    ("identity", (112, 112), TEMPLATE.copy(), "points already on the template: the crop is the picture"),    ("larger", (320, 240), placed(2.0, 0, (150, 120)), "a face twice the template's size"),    ("turned", (300, 300), placed(1.6, 20, (150, 160)), "turned 20 degrees"),    ("small-turned", (360, 270), placed(0.45, -35, (200, 90)), "a small face (about 16 px between the eyes), turned -35 degrees"),    ("jittered", (400, 300), placed(1.3, 8, (210, 140), jitter=1.5, seed=7), "points off the template by noise: least squares"),    ("edge", (200, 150), placed(1.2, 0, (20, 30)), "a face at the corner: the crop reaches outside the picture (black)"),]def main():    ap = argparse.ArgumentParser()    ap.add_argument("--out", required=True)    out = Path(ap.parse_args().out)    out.mkdir(parents=True, exist_ok=True)    cases = []    for n, (name, (w, h), pts, why) in enumerate(CASES):        img = picture(w, h, pts, n)        a, b, tx, ty = similarity(pts, TEMPLATE)        c = crop(img.astype(np.float64), a, b, tx, ty)        Image.fromarray(img, "RGB").save(out / f"{name}-source.png", optimize=True)        Image.fromarray(c, "RGB").save(out / f"{name}-crop.png", optimize=True)        cases.append(dict(            name=name, why=why, width=w, height=h,            source=f"{name}-source.png", source_rgb_sha256=hashlib.sha256(img.tobytes()).hexdigest(),            points=[[round(float(x), 6), round(float(y), 6)] for x, y in pts],            transform=dict(a=float(a), b=float(b), tx=float(tx), ty=float(ty)),            crop=f"{name}-crop.png", crop_rgb_sha256=hashlib.sha256(c.tobytes()).hexdigest()))    refusal = dict(name="no-spread", why="all five points the same: an error, never a crop", width=112, height=112,                   points=[[50.0, 60.0]] * 5, error=True)    doc = dict(        about="Face crop and alignment test vectors for the Rust core (scripts/albums-align-vectors.py; README.md).",        template=dict(side=SIDE, points=TEMPLATE.tolist(), order=["eye left in picture", "other eye", "nose tip",                                                                   "mouth corner left in picture", "other corner"]),        coordinates="pixel index: the centre of the top-left pixel is (0, 0); x right, y down",        interpolation="bilinear over pixel centres; outside the picture is black; round halves away from zero; clamp",        tolerance=dict(transform=1e-4, crop_byte=1),        cases=cases + [refusal])    (out / "vectors.json").write_text(json.dumps(doc, indent=2) + "\n")    print(f"{len(cases)} cases and one refusal in {out}")if __name__ == "__main__":    main()