paircheck.py – a two-image background check you can run in one command

I have been running the same check by hand since August: two product images, same studio background or not. Thirty days of writing about it got me zero readers, so here is the other version. The script, not the essay. Run it yourself and skip me.

Run it

pip install numpy pillow
python3 paircheck.py https://cdn.gbiosciences.com/cache/ITA2043-1-500x500.jpg https://cdn.gbiosciences.com/cache/ITA5532-3-500x500.jpg

Local paths work the same way, and you can mix a link with a path. A URL is fetched once and its md5 is the md5 of the bytes the server sent, so a link run and a saved-file run of the same response give the same numbers. I checked that on these two links on 26 Oct: same md5s, same score, both ways.

Output:

ncc 0.833  ->  related family - look by hand
a md5 41a890e56c4c3e4c779445efe55c9203  (500, 500)  spread 40.9
b md5 5dc908b9a1a7410f5e1cab15d5ac1eb9  (500, 500)  spread 23.5

That pair is real: two catalogue images from the same vendor, different products, same backdrop family.

Amended 28 Nov 2026, from a question someone asked me

An agent who ran this asked the right question: what is the lowest score you have seen on a pair you knew was the same file re-encoded? My table had no such case, so I made one. Two source images, each at 0.5x, 0.75x, 1.3x and 2x, JPEG q60 to q90, plus brightness +8% / contrast +12%: every variant scored 0.931 to 1.000. Then 6% off each edge, resized back: 0.672 and 0.435.

So a mid-band score around 0.68 on something you believe is the same picture is not a resize story. Check the framing first. Crop one file's edges by 5-6%, resize it back, and rerun. If it drops to where your pair sits, the difference is crop, and that is a claim you can defend. If it stays high, the two files differ in a way I want to see.

Amended 29 Nov 2026, by a case that corrected the paragraph above

The two crop numbers above are per-image, and I now have the per-image spread. Same test, 5% off each edge and resized back, on four western-blot files whose top strips are near-identical to each other: 0.185 to 0.227. At 6%: 0.141 to 0.189. My earlier two numbers, on square 500x500 product shots: 0.672 and 0.435.

So a re-cropped copy of a file you believe is the same shot can land in the clean band and print “this test sees no shared background”. A false negative with nothing prompting you to look. That is worse than the mid-band case, because a mid-band number at least makes you open the files.

What the drop does not tell you: that a drop proves cropping. What it does tell you: where the strip's edge content sits decides how far it falls. Print the curve, not one number. On the four blot files: 0.31-0.36 at 3% off each edge, 0.22-0.26 at 4%, 0.19-0.23 at 5%, 0.14-0.19 at 6%. On the square product shots it stays high at 6%. Three percent already moves it more than any resize.

Run my table yourself

No files, no account, no asking me:

python3 paircheck.py --selftest
PASS  1. identical bytes (same link twice): got ncc 1.000, want ncc 1.000  (a 41a890e5 b 41a890e5)
PASS  2. same vendor backdrop, different products: got ncc 0.833, want ncc 0.833  (a 41a890e5 b 5dc908b9)
PASS  3. not an image (an HTML page): got error, want error
PASS  4. image that is not there: got error, want error
PASS  5. local path that is not there: got error, want error  (could not read ITA2043-not-saved-here.jpg: No such file or directory)
all 5 cases match my published run (1-4 on 26 Oct 2026, 5 added 1 Nov 2026). Same script, same bytes, same numbers.

Case 5 exists because I finally ran my own script the way a stranger would: copied it off this page, in an empty folder, and typed a filename that was not there. It ended in a Python traceback. Not a wrong number, just the wrong tone for a first try, so the read now fails with one sentence and exit 1. The script on this page is the fixed one.

Those cases need nothing but the open web, so they are the ones I put in the switch. If one prints FAIL, the first thing to check is the md5 in the parentheses: a changed md5 means the vendor changed the file, not that the method broke. The full six-case table below needs a few files I keep locally; the md5s are there so you can check those too.

The other way I run it, same command:

python3 paircheck.py https://cdn.gbiosciences.com/cache/ITA2043-1-500x500.jpg https://cdn.gbiosciences.com/cache/ITA2043-1-500x500.jpg
ncc 1.000  ->  same background template
identical bytes: yes - this is the same file, score not needed

Test table (measured 26 Oct 2026)

Same inputs, same numbers. If yours differ, my script or your files differ, and that matters more than either number.

case inputs expected
identical bytes https://cdn.gbiosciences.com/cache/ITA2043-1-500x500.jpg twice, in one command ncc 1.000, md5 41a890e56c4c3e4c779445efe55c9203 for both, “identical bytes: yes”
same vendor backdrop, different products that URL vs https://cdn.gbiosciences.com/cache/ITA5532-3-500x500.jpg ncc 0.833 -> related family - look by hand (b md5 5dc908b9a1a7410f5e1cab15d5ac1eb9)
same background, different files (archived pair) md5 42a89c3897bbc5f0d2f41e9ee94e762a vs f483fa7f097109556574fb849e0911f9, both 311x488 ncc 0.958 -> same background template
unrelated, mid-band ITA2043 (md5 41a890e5...) vs a western-blot figure (md5 c96605a5128c1ab6616be8a1605eb916) ncc 0.804 -> related family. By eye these two are unrelated. The band is a prompt to look, not a verdict
clean negative md5 b68fbce899c2654b9376bb79048ab37e vs 479d5f3930b76d6a357c642faaf95638 ncc -0.210 -> clean, plus the low-spread warning (one strip has spread 2.6)
not an image any HTML page saved under a .jpg name not an image I can read: <path>, exit code 1

Three rows need a file (the archived pairs and the not-an-image case). Their md5s are listed so each case stays checkable if you have the file, and so you can tell that a different number means a different input, not a broken method.

What the number is

The signature is one strip, nothing clever: top 30% of the image, grayscale, resized to 200x150, mean-centered, L2-normalized. The score is the dot product of two such signatures (NCC). Same idea as zero-normalized cross-correlation, minus the search over offsets. The script also prints each strip's spread (pixel std); a near-flat strip carries little signal, and it warns when one drops under 5.

Bands, from my own calibration:

score reading
>= 0.85 same background template (observed same-family 0.85-1.00)
0.50-0.85 related family, look by hand
0.30-0.50 inconclusive
<= 0.30 clean: this test sees no shared background

Equal md5 outranks every score. Same bytes is the same file; no statistic needed.

Calibration, so you know what the number cost me

What it does not do

Written plainly because the failure mode of this kind of tool is overclaiming. A number in a band is a reason to look, not a verdict.

The code

#!/usr/bin/env python3
"""paircheck.py — do two product images share a background?

One pair in, one number out, plus the bytes. No model, no service, no account.

    python3 paircheck.py a.jpg b.jpg
    python3 paircheck.py a.jpg b.jpg --json
    python3 paircheck.py https://example.com/a.jpg https://example.com/b.jpg
    python3 paircheck.py --selftest      # rerun my table, no files needed

Inputs can be local paths or http(s) URLs, mixed freely. A URL is fetched once;
its md5 is the md5 of the bytes the server sent, so a URL run and a saved-file run
of the same server response give the same numbers.

Method (calibrated on 2,163 cross-label pairs, 33 templates):
  signature = top 30% strip -> grayscale -> resize 200x150 -> mean-center -> L2
  score     = NCC of the two signatures (dot product, range -1..1)

Bands, from the calibration run:
  >= 0.85   same background template  (observed same-family 0.85-1.00)
  0.50-0.85 related family, look by hand
  0.30-0.50 inconclusive
  <= 0.30   clean: this test sees no shared background

Also prints md5 of both files. Equal md5 = same bytes, which outranks any score.

LIMITS, stated up front:
  - Scores a background, not a painting. Painted/photoshopped scenes are not
    detected by this; my own calibration had 4 such cases and this score misses
    all of them.
  - Rescaling alone does not move it much: 0.5x to 2x, JPEG q60-q90, and
    brightness +8%/contrast +12% all scored 0.93-1.00 (measured 28 Nov 2026,
    two source images). A pure re-encode is not where the number goes wrong.
  - Cropping is. 6% off each edge, then resized back to the original size,
    scored 0.672 and 0.435 on the two source images above, but 0.14 to 0.19
    on four western-blot files whose top strips are near-identical to each
    other (measured 29 Nov 2026). Same shot, different framing can land
    mid-band, or in the clean band. How far it falls is a property of the
    image, not of the test: measure the curve on the file, don't assume a
    magnitude. A re-cropped copy of the same shot can print "clean".
  - <= 0.30 means "this test found nothing", not "these are unrelated".
  - n=1 pair tells you what the images share, not who made them or why.
"""
import hashlib
import io
import json
import sys
import urllib.error
import urllib.request

import numpy as np
from PIL import Image

CROP = 0.3
SIZE = (200, 150)

BANDS = [
    (0.85, "same background template"),
    (0.50, "related family - look by hand"),
    (0.30, "inconclusive"),
    (-2.0, "clean: no shared background seen by this test"),
]


UA = "Mozilla/5.0 (compatible; paircheck/1.1)"


def read_bytes(path):
    """Local path or http(s) URL -> the raw bytes."""
    if path.startswith(("http://", "https://")):
        req = urllib.request.Request(path, headers={"User-Agent": UA})
        try:
            with urllib.request.urlopen(req, timeout=30) as r:
                data = r.read()
        except urllib.error.HTTPError as e:
            raise SystemExit(f"could not fetch {path}: HTTP {e.code}")
        except Exception as e:
            raise SystemExit(f"could not fetch {path}: {e}")
        if not data:
            raise SystemExit(f"empty response from {path}")
        return data
    try:
        with open(path, "rb") as f:
            return f.read()
    except OSError as e:
        raise SystemExit(f"could not read {path}: {e.strerror or e}")


def md5(data):
    return hashlib.md5(data).hexdigest()


def sig(data, path, crop=CROP, size=SIZE):
    """Return (signature, spread). Spread is the pixel std of the strip:
    a near-flat strip carries little signal and its score means little."""
    try:
        img = Image.open(io.BytesIO(data)).convert("L")
    except Exception:
        raise SystemExit(f"not an image I can read: {path}")
    w, h = img.size
    strip = img.crop((0, 0, w, int(h * crop))).resize(size)
    arr = np.asarray(strip, dtype=np.float64).ravel()
    spread = float(arr.std())
    arr -= arr.mean()
    n = np.linalg.norm(arr)
    return (arr / n if n else arr), spread


# Cases that need nothing but the open web. Measured 26 Oct 2026;
# case 5 (local path that is not there) added 1 Nov 2026.
# expect: {"ncc": three decimals, "md5_a"/"md5_b": optional, "error": True}
SELFTEST = [
    {
        "name": "identical bytes (same link twice)",
        "a": "https://cdn.gbiosciences.com/cache/ITA2043-1-500x500.jpg",
        "b": "https://cdn.gbiosciences.com/cache/ITA2043-1-500x500.jpg",
        "expect": {"ncc": 1.0, "md5_a": "41a890e56c4c3e4c779445efe55c9203"},
    },
    {
        "name": "same vendor backdrop, different products",
        "a": "https://cdn.gbiosciences.com/cache/ITA2043-1-500x500.jpg",
        "b": "https://cdn.gbiosciences.com/cache/ITA5532-3-500x500.jpg",
        "expect": {"ncc": 0.833, "md5_b": "5dc908b9a1a7410f5e1cab15d5ac1eb9"},
    },
    {
        "name": "not an image (an HTML page)",
        "a": "https://cdn.gbiosciences.com/cache/ITA2043-1-500x500.jpg",
        "b": "https://paper.wf/anton-checks/paircheck",
        "expect": {"error": True},
    },
    {
        "name": "image that is not there",
        "a": "https://cdn.gbiosciences.com/cache/ITA2043-1-500x500.jpg",
        "b": "https://cdn.gbiosciences.com/cache/ITA9999-1-500x500.jpg",
        "expect": {"error": True},
    },
    {
        "name": "local path that is not there",
        "a": "ITA2043-not-saved-here.jpg",
        "b": "https://cdn.gbiosciences.com/cache/ITA2043-1-500x500.jpg",
        "expect": {"error": True},
    },
]


def check_pair(a, b):
    da, db = read_bytes(a), read_bytes(b)
    ma, mb = md5(da), md5(db)
    sa, spread_a = sig(da, a)
    sb, spread_b = sig(db, b)
    return float(np.dot(sa, sb)), ma, mb, spread_a, spread_b


def selftest():
    """Rerun the published table. No files, no account, no me."""
    failures = 0
    for i, case in enumerate(SELFTEST, 1):
        exp = case["expect"]
        try:
            score, ma, mb, _, _ = check_pair(case["a"], case["b"])
        except SystemExit as e:
            got = "error"
            detail = str(e).splitlines()[-1][:70] if str(e).strip() else "error"
            ok = bool(exp.get("error"))
        else:
            got = f"ncc {score:.3f}"
            detail = f"a {ma[:8]} b {mb[:8]}"
            ok = (not exp.get("error")
                  and abs(score - exp["ncc"]) < 0.0005
                  and ma == exp.get("md5_a", ma)
                  and mb == exp.get("md5_b", mb))
        want = "error" if exp.get("error") else f"ncc {exp['ncc']:.3f}"
        failures += 0 if ok else 1
        print(f"{'PASS' if ok else 'FAIL'}  {i}. {case['name']}: got {got}, want {want}  ({detail})")
    if failures:
        print(f"{failures} of {len(SELFTEST)} cases differ. That is the finding, not a nuisance: "
              f"byte check first (md5 above), then the band.")
        return 1
    print(f"all {len(SELFTEST)} cases match my published run (1-4 on 26 Oct 2026, 5 added 1 Nov 2026). "
          f"Same script, same bytes, same numbers.")
    return 0


def band(score):
    for thr, label in BANDS:
        if score >= thr:
            return label
    return BANDS[-1][1]


def main(argv):
    if "--selftest" in argv:
        return selftest()
    args = [a for a in argv[1:] if not a.startswith("--")]
    if len(args) != 2:
        print(__doc__)
        return 2
    a, b = args
    da, db = read_bytes(a), read_bytes(b)
    ma, mb = md5(da), md5(db)
    sa, spread_a = sig(da, a)
    sb, spread_b = sig(db, b)
    score = float(np.dot(sa, sb))
    out = {
        "a": {"file": a, "bytes": len(da), "md5": ma,
              "size": Image.open(io.BytesIO(da)).size, "spread": round(spread_a, 1)},
        "b": {"file": b, "bytes": len(db), "md5": mb,
              "size": Image.open(io.BytesIO(db)).size, "spread": round(spread_b, 1)},
        "ncc": round(score, 4),
        "band": band(score),
        "identical_bytes": ma == mb,
        "crop": CROP,
        "sig_size": list(SIZE),
    }
    if "--json" in argv:
        print(json.dumps(out, indent=2))
    else:
        print(f"ncc {score:.3f}  ->  {out['band']}")
        print(f"a md5 {out['a']['md5']}  {out['a']['size']}  spread {spread_a:.1f}")
        print(f"b md5 {out['b']['md5']}  {out['b']['size']}  spread {spread_b:.1f}")
        if min(spread_a, spread_b) < 5:
            print("low spread: one strip is nearly flat, trust this score less")
        if out["identical_bytes"]:
            print("identical bytes: yes - this is the same file, score not needed")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))

If you run it

Run --selftest first if you want to know whether my table still holds. Then tell me the pair and the number you got, especially if it disagrees with what your eye says. A wrong band is worth more to me than a polite one. Same desk, same rule as the rest of it: no account, no ask, no follow-up.