"""digitize_a.py -- Reading A (automatic), RULES_digitize.txt and RULES_digitize_layout.txt. py -3.12 -I digitize_a.py Spines: rows/columns that are dark over most of the frame. Ticks: dark runs drawn inward from the spines; a tick's pixel position is the length-weighted mean of its columns (x) or rows (y). Major ticks (>= 13 px long) are assigned values in order from the layout note; the spines carry the end labels where the layout note says so. Markers: colour thresholds from the layout note, connected components (scipy.ndimage.label) inside the frame inset by 6 px, area >= 150 px, bounding-box aspect 0.7-1.4, fill fraction >= 0.6; the point is the component's centroid. Calibration: least squares through labelled ticks, residual check 0.5% of axis length. Shares no code with digitize_b.py except Pillow. """ import json import math import os import sys import numpy as np from PIL import Image from scipy import ndimage DARK = 128 # spine/tick detection threshold (grey level) MAJOR = 13 # px: a tick at least this long is a major tick MINOR_MIN = 4 def load(path): im = Image.open(path) rgb = np.asarray(im.convert("RGB")).astype(float) grey = np.asarray(im.convert("L")).astype(float) return rgb, grey def groups(idx): """Split sorted integer indices into runs of consecutive values.""" out, cur = [], [int(idx[0])] for i in idx[1:]: if i == cur[-1] + 1: cur.append(int(i)) else: out.append(cur) cur = [int(i)] out.append(cur) return out def spines(grey): dark = grey < DARK col = dark.sum(axis=0) row = dark.sum(axis=1) cg = groups(np.where(col > 0.5 * col.max())[0]) rg = groups(np.where(row > 0.5 * row.max())[0]) left, right = cg[0], cg[-1] top, bottom = rg[0], rg[-1] def centre(g, prof): w = prof[g].astype(float) return float((np.array(g) * w).sum() / w.sum()) return {"left": (left[0], left[-1], centre(left, col)), "right": (right[0], right[-1], centre(right, col)), "top": (top[0], top[-1], centre(top, row)), "bottom": (bottom[0], bottom[-1], centre(bottom, row))} def ticks_x(grey, sp): """Ticks rising from the bottom spine: for each column, the dark run length just above the spine.""" dark = grey < DARK y_in = sp["bottom"][0] - 1 x0, x1 = sp["left"][1] + 3, sp["right"][0] - 3 lengths = np.zeros(grey.shape[1]) for x in range(x0, x1 + 1): n = 0 y = y_in while y > 0 and dark[y, x] and n < 40: n += 1 y -= 1 lengths[x] = n return tick_groups(lengths) def ticks_y(grey, sp): """Ticks from the left spine: for each row, the dark run length just right of the spine.""" dark = grey < DARK x_in = sp["left"][1] + 1 y0, y1 = sp["top"][1] + 3, sp["bottom"][0] - 3 lengths = np.zeros(grey.shape[0]) for y in range(y0, y1 + 1): n = 0 x = x_in while x < grey.shape[1] and dark[y, x] and n < 40: n += 1 x += 1 lengths[y] = n return tick_groups(lengths) def tick_groups(lengths): idx = np.where(lengths >= MINOR_MIN)[0] out = [] if len(idx) == 0: return out for g in groups(idx): w = lengths[g] out.append({"px": float((np.array(g) * w).sum() / w.sum()), "length": float(w.max()), "width": len(g), "major": bool(w.max() >= MAJOR)}) return out def fit(pairs, log): u = np.array([math.log10(v) if log else v for v, _ in pairs], dtype=float) p = np.array([px for _, px in pairs], dtype=float) m, s = u.mean(), u.std() # standardise: linear axes carry values ~1e22 (ill-conditioned otherwise) z = (u - m) / s A = np.vstack([np.ones_like(z), z]).T (a0, b0), *_ = np.linalg.lstsq(A, p, rcond=None) b = b0 / s a = a0 - b * m return float(a), float(b), (p - (a0 + b0 * z)).tolist() def value(px, a, b, log): u = (px - a) / b return 10 ** u if log else u def components(mask, frame, min_area=150, fill_min=0.6): lab, n = ndimage.label(mask) out = [] for k in range(1, n + 1): ys, xs = np.where(lab == k) if len(xs) < min_area: continue w, h = xs.max() - xs.min() + 1, ys.max() - ys.min() + 1 aspect = w / h fill = len(xs) / (w * h) if not (0.7 <= aspect <= 1.4) or fill < fill_min: continue out.append({"cx": float(xs.mean()), "cy": float(ys.mean()), "area": int(len(xs)), "w": int(w), "h": int(h), "fill": round(float(fill), 3), "bbox_cx": float((xs.min() + xs.max()) / 2), "bbox_cy": float((ys.min() + ys.max()) / 2)}) return sorted(out, key=lambda c: c["cx"]) def inset_mask(shape, sp, inset=6): m = np.zeros(shape, bool) m[sp["top"][1] + inset:sp["bottom"][0] - inset, sp["left"][1] + inset:sp["right"][0] - inset] = True return m SPEC = { # x: (log, list of values for major ticks left to right, spine labels); y: (log, values for majors bottom to top) "fig4": {"image": "apjaeb6abf4_hr.jpg", "x_log": True, "y_log": True, "x_major_values": [1e-4, 1e-3, 1e-2, 1e-1, 1, 10, 100], "x_left_spine": 1e-5, "x_labelled": [1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1, 10, 100], "y_major_values_bottom_up": [1e19, 1e20, 1e21, 1e22, 1e23, 1e24, 1e25, 1e26], "y_bottom_spine": 1e18, "y_labelled": [1e18, 1e20, 1e22, 1e24, 1e26]}, "fig5": {"image": "apjaeb6abf5_hr.jpg", "x_log": False, "y_log": False, "x_major_values": [0, 30, 60, 90, 120, 150, 180], "x_labelled": [0, 30, 60, 90, 120, 150, 180], "y_major_values_bottom_up": [5.0e21, 1.0e22, 1.5e22, 2.0e22], "y_top_spine": 2.5e22, "y_labelled": [5.0e21, 1.0e22, 1.5e22, 2.0e22, 2.5e22]}, "fig6": {"image": "apjaeb6abf6_hr.jpg", "x_log": False, "y_log": True, "x_major_values": [0, 30, 60, 90, 120, 150, 180], "x_labelled": [0, 30, 60, 90, 120, 150, 180], "y_major_values_bottom_up": [1e22, 1e23], "y_labelled": [1e22, 1e23]}, } def run(img_dir, out_dir): res = {} for fig, s in SPEC.items(): rgb, grey = load(os.path.join(img_dir, s["image"])) sp = spines(grey) tx = ticks_x(grey, sp) ty = ticks_y(grey, sp) mx = [t for t in tx if t["major"]] my = sorted([t for t in ty if t["major"]], key=lambda t: -t["px"]) # bottom (large y) first if len(mx) != len(s["x_major_values"]) or len(my) != len(s["y_major_values_bottom_up"]): raise SystemExit("%s: found %d x and %d y major ticks; expected %d and %d" % ( fig, len(mx), len(my), len(s["x_major_values"]), len(s["y_major_values_bottom_up"]))) xpairs = [(v, t["px"]) for v, t in zip(s["x_major_values"], mx)] if "x_left_spine" in s: xpairs.append((s["x_left_spine"], sp["left"][2])) ypairs = [(v, t["px"]) for v, t in zip(s["y_major_values_bottom_up"], my)] if "y_bottom_spine" in s: ypairs.append((s["y_bottom_spine"], sp["bottom"][2])) if "y_top_spine" in s: ypairs.append((s["y_top_spine"], sp["top"][2])) xl = [(v, p) for v, p in xpairs if any(abs(v - L) <= 1e-9 * max(1, abs(L)) for L in s["x_labelled"])] yl = [(v, p) for v, p in ypairs if any(abs(v - L) <= 1e-9 * max(1, abs(L)) for L in s["y_labelled"])] ax_a, ax_b, ax_res = fit(xl, s["x_log"]) ay_a, ay_b, ay_res = fit(yl, s["y_log"]) xlen = sp["right"][2] - sp["left"][2] ylen = sp["bottom"][2] - sp["top"][2] cal = {"x": {"a": ax_a, "b": ax_b, "residuals_px": ax_res, "max_frac": max(map(abs, ax_res)) / xlen, "pass": max(map(abs, ax_res)) / xlen <= 0.005, "ticks_used": xl}, "y": {"a": ay_a, "b": ay_b, "residuals_px": ay_res, "max_frac": max(map(abs, ay_res)) / ylen, "pass": max(map(abs, ay_res)) / ylen <= 0.005, "ticks_used": yl}, "spines": sp, "unlabelled_major_y": [(v, p) for v, p in ypairs if (v, p) not in yl]} frame = inset_mask(grey.shape, sp) R, G, B = rgb[..., 0], rgb[..., 1], rgb[..., 2] if fig == "fig6": black = (R < 100) & (G < 100) & (B < 100) & frame blue = (B > 150) & (R < 120) & (G < 120) & frame else: black = (grey < 100) & frame blue = None pts = [] for c in components(black, frame): c["series"] = "black" pts.append(c) if blue is not None: for c in components(blue, frame, fill_min=0.8): c["series"] = "blue" pts.append(c) # the 0-degree black circle is partly hidden by the blue square: take the black ring around it if not any(p["series"] == "black" and p["cx"] < sp["left"][2] + 80 for p in pts): sq = [p for p in pts if p["series"] == "blue"][0] win = np.zeros_like(frame) y0, y1 = int(sq["bbox_cy"]) - 20, int(sq["bbox_cy"]) + 21 x0, x1 = int(sq["bbox_cx"]) - 20, int(sq["bbox_cx"]) + 21 win[y0:y1, x0:x1] = True ring = black & win ys, xs = np.where(ring) pts.append({"cx": float(xs.mean()), "cy": float(ys.mean()), "area": int(len(xs)), "bbox_cx": float((xs.min() + xs.max()) / 2), "bbox_cy": float((ys.min() + ys.max()) / 2), "w": int(xs.max() - xs.min() + 1), "h": int(ys.max() - ys.min() + 1), "series": "black", "note": "visible ring around the blue square"}) for p in pts: p["x"] = value(p["cx"], ax_a, ax_b, s["x_log"]) p["y"] = value(p["cy"], ay_a, ay_b, s["y_log"]) p["y_bbox"] = value(p["bbox_cy"], ay_a, ay_b, s["y_log"]) pts.sort(key=lambda p: (p["series"], p["cx"])) minor_check = [] if fig == "fig6": for t in ty: if t["major"]: continue v = value(t["px"], ay_a, ay_b, True) e = math.floor(math.log10(v)) mant = round(v / 10 ** e) if 2 <= mant <= 9: pred = ay_a + ay_b * math.log10(mant * 10 ** e) minor_check.append({"value": mant * 10 ** e, "px": t["px"], "residual_px": t["px"] - pred}) res[fig] = {"calibration": cal, "points": pts, "ticks_x": tx, "ticks_y": ty, "minor_check": minor_check} print(fig, "x pass", cal["x"]["pass"], "%.4f" % cal["x"]["max_frac"], "y pass", cal["y"]["pass"], "%.4f" % cal["y"]["max_frac"], "spines", {k: round(v[2], 1) for k, v in sp.items()}) for p in pts: print(" %-5s x=%8.4g y=%10.4g (px %.1f, %.1f; area %d; bbox-centre y=%.4g)%s" % ( p["series"], p["x"], p["y"], p["cx"], p["cy"], p["area"], p["y_bbox"], (" [" + p["note"] + "]") if "note" in p else "")) if minor_check: print(" minor ticks: max |residual| %.2f px over %d ticks" % ( max(abs(m["residual_px"]) for m in minor_check), len(minor_check))) with open(os.path.join(out_dir, "reading_a.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(res, f, indent=1, default=float) if __name__ == "__main__": run(sys.argv[1], sys.argv[2])