"""digitize_b.py -- Reading B (by eye), RULES_digitize.txt. Mode "sheets": python3 -I digitize_b.py sheets For every item (marker or tick) listed with an approximate centre in approx.json, crops a small region of the image, enlarges it 10x and draws a grid every 2 px (light) and 4 px (dark), labelled with absolute pixel coordinates, so that the centre can be read by eye. Tiles are assembled into sheets (PNG, local only). Mode "compute": python3 -I digitize_b.py compute Takes the by-eye pixel positions, fits each axis by least squares through its labelled ticks, checks the residuals (0.5% of the axis length) and converts the marker centres to values. Writes out/reading_b.json. Standard library + Pillow only. No code shared with digitize_a.py except Pillow's image loader. """ import json import math import os import sys from PIL import Image, ImageDraw, ImageFont ZOOM = 10 def tile(im, cx, cy, r, title): x0, y0 = int(round(cx)) - r, int(round(cy)) - r box = (x0, y0, x0 + 2 * r + 1, y0 + 2 * r + 1) crop = im.crop(box).convert("RGB").resize(((2 * r + 1) * ZOOM, (2 * r + 1) * ZOOM), Image.NEAREST) pad = 46 W, H = crop.size[0] + pad, crop.size[1] + pad + 18 out = Image.new("RGB", (W, H), (255, 255, 255)) out.paste(crop, (pad, pad + 18)) d = ImageDraw.Draw(out) font = ImageFont.load_default() d.text((2, 2), title, fill=(0, 0, 0), font=font) for k in range(2 * r + 2): px = x0 + k X = pad + k * ZOOM Y = pad + 18 + k * ZOOM if px % 2 == 0: col = (255, 150, 150) if px % 4 else (200, 0, 0) d.line([(X, pad + 18), (X, H)], fill=col, width=1) if px % 4 == 0: d.text((X - 8, pad + 4), str(px), fill=(200, 0, 0), font=font) py = y0 + k if py % 2 == 0: col = (150, 150, 255) if py % 4 else (0, 0, 200) d.line([(pad, Y), (W, Y)], fill=col, width=1) if py % 4 == 0: d.text((2, Y - 5), str(py), fill=(0, 0, 200), font=font) return out def sheets(approx_path, img_dir, out_dir): with open(approx_path, encoding="utf-8") as f: approx = json.load(f) for fig, spec in approx.items(): im = Image.open(os.path.join(img_dir, spec["image"])) tiles = [] for item in spec["items"]: name, cx, cy, r = item["name"], item["x"], item["y"], item.get("r", 16) tiles.append(tile(im, cx, cy, r, "%s %s (crop centre %d,%d)" % (fig, name, cx, cy))) per_sheet = 4 for s in range(0, len(tiles), per_sheet): group = tiles[s:s + per_sheet] W = sum(t.size[0] for t in group) + 10 * (len(group) - 1) H = max(t.size[1] for t in group) sheet = Image.new("RGB", (W, H), (255, 255, 255)) x = 0 for t in group: sheet.paste(t, (x, 0)) x += t.size[0] + 10 path = os.path.join(out_dir, "sheetB_%s_%02d.png" % (fig, s // per_sheet)) sheet.save(path) print(path, sheet.size) def fit(ticks, log): """Least squares pixel = a + b * u, u = log10(value) or value. Returns (a, b, residuals in px).""" us = [math.log10(t["value"]) if log else t["value"] for t in ticks] ps = [t["px"] for t in ticks] n = len(us) mu, mp = sum(us) / n, sum(ps) / n suu = sum((u - mu) ** 2 for u in us) b = sum((u - mu) * (p - mp) for u, p in zip(us, ps)) / suu a = mp - b * mu res = [p - (a + b * u) for u, p in zip(us, ps)] return a, b, res def compute(pix_path, out_dir): with open(pix_path, encoding="utf-8") as f: pix = json.load(f) result = {} for fig, spec in pix.items(): if fig.startswith("_"): continue ax = {} for axis in ("x", "y"): a, b, res = fit(spec[axis + "_ticks"], spec[axis + "_log"]) length = abs(spec[axis + "_axis_length_px"]) ax[axis] = {"a": a, "b": b, "residuals_px": res, "max_residual_frac": max(abs(r) for r in res) / length, "check_pass": max(abs(r) for r in res) / length <= 0.005} pts = [] for m in spec["markers"]: vals = {} for axis, key in (("x", "px_x"), ("y", "px_y")): u = (m[key] - ax[axis]["a"]) / ax[axis]["b"] vals[axis] = 10 ** u if spec[axis + "_log"] else u pts.append({"name": m["name"], "series": m.get("series", ""), "px_x": m["px_x"], "px_y": m["px_y"], "x": vals["x"], "y": vals["y"]}) extra = {} for chk in spec.get("y_minor_check", []): u = (chk["px"] - ax["y"]["a"]) / ax["y"]["b"] extra[str(chk["value"])] = {"px": chk["px"], "implied": 10 ** u if spec["y_log"] else u, "residual_px": chk["px"] - (ax["y"]["a"] + ax["y"]["b"] * ( math.log10(chk["value"]) if spec["y_log"] else chk["value"]))} result[fig] = {"axes": ax, "points": pts, "minor_tick_check": extra} path = os.path.join(out_dir, "reading_b.json") with open(path, "w", encoding="utf-8", newline="\n") as f: json.dump(result, f, indent=1) for fig, r in result.items(): print(fig, "x check", r["axes"]["x"]["check_pass"], "%.4f" % r["axes"]["x"]["max_residual_frac"], "y check", r["axes"]["y"]["check_pass"], "%.4f" % r["axes"]["y"]["max_residual_frac"]) for p in r["points"]: print(" %-8s %-6s x=%.4g y=%.4g" % (p["name"], p["series"], p["x"], p["y"])) for k, v in r["minor_tick_check"].items(): print(" minor", k, "implied %.4g residual %.2f px" % (v["implied"], v["residual_px"])) if __name__ == "__main__": if sys.argv[1] == "sheets": sheets(sys.argv[2], sys.argv[3], sys.argv[4]) else: compute(sys.argv[2], sys.argv[3])