# -*- coding: utf-8 -*- """Воспроизводимая оцифровка графиков ГОСТ 34233.4-2017, использованных в calc/gost34233_4.py: рис. К.2 (β_F, скан p040), К.3 (β_V, p041), К.4 (f, p041), Л.1 (M_кр, p044). Запуск: python3 calc/tests/digitize_figs_gost34233_4.py [--overlay DIR] Печатает таблицы и максимальное расхождение с таблицами модуля; с --overlay сохраняет PNG с наложением восстановленных кривых (красным) на скан для визуальной проверки. Методика: бинаризация (порог 128) -> морфологическое открытие 6×6 (7×7 для Л.1): линии сетки толщиной 4—5 px исчезают, кривые толщиной 7—10 px остаются -> положения кривых по столбцам (рис. К.4 — по строкам), присвоение подписей по порядку кривых в столбцах, где видны все кривые -> привязка пикселей к значениям по линиям сетки с подписанными значениями (кусочно-линейная; для К.4 по логарифму f) -> сглаживающий сплайн с отбраковкой выбросов. Подписи линий сетки назначены по подписям осей на сканах (см. константы BV_*, FV_* ниже). """ from __future__ import annotations import os import sys import numpy as np from PIL import Image, ImageDraw from scipy import ndimage as ndi from scipy.interpolate import PchipInterpolator, UnivariateSpline from scipy.optimize import brentq HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.dirname(HERE)) import gost34233_4 as g4 # noqa: E402 SCAN = os.path.join(os.path.dirname(os.path.dirname(HERE)), "norm", "src", "gost34233_4", "gost34233.4-2017") NODES = [1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.8, 2.0, 2.25, 2.5, 2.75, 3.0, 3.5, 4.0, 4.5, 5.0] def load(page): return np.array(Image.open(os.path.join(SCAN, page + ".png")).convert("L")) def groups(idx): out, cur = [], [] for a in idx: if cur and a - cur[-1] > 1: out.append((cur[0], cur[-1])) cur = [] cur.append(a) if cur: out.append((cur[0], cur[-1])) return out def gridlines(im, y0, y1, x0, x1, frac=0.5): dark = im[y0:y1, x0:x1] < 128 return (groups(list(np.where(dark.mean(axis=0) > frac)[0] + x0)), groups(list(np.where(dark.mean(axis=1) > frac)[0] + y0))) def runs1d(col): r, s = [], None for i, v in enumerate(col): if v and s is None: s = i if not v and s is not None: r.append((s, i - 1)) s = None if s is not None: r.append((s, len(col) - 1)) return r def centers(o, x, y0, hgrid, thick=7): out = [] for a, b in runs1d(o[:, x]): A, B = a + y0, b + y0 L = B - A + 1 if L < 5: continue c = 0.5 * (A + B) if L > thick + 1: for g0, g1 in hgrid: if g0 - 1 <= A <= g1 + 1 and B > g1 + 1: c = B - (thick - 1) / 2.0 break if g0 - 1 <= B <= g1 + 1 and A < g0 - 1: c = A + (thick - 1) / 2.0 break else: n = int(round(L / float(thick))) if n >= 2: out += [A + (k + 0.5) * L / n for k in range(n)] continue out.append(c) return out def track(o, y0, x_start, x_end, seeds, hgrid, tol=3.0, max_gap=8, step=-1, thick=7): hist = [[(x_start, s)] for s in seeds] alive, gap = [True] * len(seeds), [0] * len(seeds) for x in range(x_start + step, x_end, step): cs = centers(o, x, y0, hgrid, thick) used = set() for i, h in enumerate(hist): if not alive[i]: continue slope = (h[-1][1] - h[-8][1]) / (h[-1][0] - h[-8][0]) if len(h) >= 8 else 0.0 pred = h[-1][1] + slope * (x - h[-1][0]) best = min(((abs(c - pred), j) for j, c in enumerate(cs) if j not in used), default=None) if best and best[0] <= tol: used.add(best[1]) h.append((x, cs[best[1]])) gap[i] = 0 else: gap[i] += 1 alive[i] = gap[i] <= max_gap return hist def spline(pts): P = np.array(sorted(pts), float) xs = np.unique(P[:, 0]) ys = np.array([P[P[:, 0] == x, 1].mean() for x in xs]) for _ in range(4): spl = UnivariateSpline(xs, ys, k=3, s=len(xs) * 0.8 ** 2) res = ys - spl(xs) ok = np.abs(res) <= max(2.5, 3 * np.sqrt(np.mean(res ** 2))) if ok.all(): break xs, ys = xs[ok], ys[ok] return spl, xs.min(), xs.max() def table(pts, vc, bv, hc, vals, origin): node_px = np.interp(NODES, bv, vc) y0px = np.interp(origin, vals[::-1], hc[::-1]) out = {} for lab, P in pts.items(): spl, xa, xb = spline(P) ya = float(spl(xa)) row = [] for b, xn in zip(NODES, node_px): if b == 1.0: row.append(origin) continue if xn < xa: yp = y0px + (ya - y0px) * (xn - vc[0]) / (xa - vc[0]) elif xn > xb: yp = float(spl(xb)) + float(spl.derivative()(xb)) * (xn - xb) else: yp = float(spl(xn)) row.append(float(np.interp(yp, hc, vals))) out[lab] = row labs = sorted(out) T = np.array([out[k] for k in labs]) for j in range(T.shape[1]): # не возрастают с ростом l/l0 T[:, j] = np.minimum.accumulate(T[:, j]) return labs, np.round(T, 4) def fig_K2(): im = load("p040") y0, y1, x0, x1 = 2080, 2990, 436, 2090 vg, hg = gridlines(im, y0, y1, x0, x1) vc = [0.5 * (a + b) for a, b in vg] hc = [0.5 * (a + b) for a, b in hg if b - a >= 3] # линии сетки S1/S0: 1,0…2,8 через 0,1 (2,9 закрыта таблицей подписей), 3,0…5,0 через 0,1 bv = [round(1.0 + 0.1 * k, 1) for k in range(19)] + [round(3.0 + 0.1 * k, 1) for k in range(21)] fv = [0.92] + [round(0.90 - 0.02 * k, 2) for k in range(21)] # ось β_F: 0,92 (верх), 0,90…0,50 assert len(bv) == len(vc) and len(fv) == len(hc) o = np.zeros_like(im, bool) o[y0:y1, x0:x1] = ndi.binary_opening(im[y0:y1, x0:x1] < 128, structure=np.ones((6, 6))) O = o[y0:y1] labels = [0.10, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.60, 0.70, 0.80, 0.90, 1.00, 1.25, 1.50, 2.00] pts = {l: [] for l in labels} xsplit = np.interp(1.30, bv, vc) full = [] for x in range(446, 2080): if any(a - 1 <= x <= b + 1 for a, b in vg): continue cs = centers(O, x, y0, hg) if len(cs) == len(labels): full.append(x) if x >= xsplit: for l, c in zip(labels, cs): pts[l].append((x, c)) # кривые, доведённые до β = 1: продолжаем трассировку влево от β = 1,25 и сопоставляем по стыку ext = {} xj = int(round(np.interp(1.25, bv, vc))) while any(a - 1 <= xj <= b + 1 for a, b in vg): xj -= 1 for l in labels: spl, xa, _ = spline(pts[l]) P = np.array([p for p in pts[l] if xa <= p[0] <= xa + 40], float) ext[l] = float(np.polyval(np.polyfit(P[:, 0], P[:, 1], 2), xj)) seeds = centers(O, xj, y0, hg) hist = track(O, y0, xj, int(np.interp(1.02, bv, vc)), seeds, hg) used = set() for s, h in zip(seeds, hist): best = min(labels, key=lambda l: abs(ext[l] - s)) if abs(ext[best] - s) <= 7 and best not in used: used.add(best) pts[best] += h return table(pts, vc, bv, hc, fv, 0.908920), (vc, bv, hc, fv) def fig_K3(): im = load("p041") y0, y1, x0, x1 = 400, 1275, 320, 1975 vg, hg = gridlines(im, y0, y1, x0, x1) vc = [0.5 * (a + b) for a, b in vg] hc = [0.5 * (a + b) for a, b in hg] bv = [round(1.0 + 0.1 * k, 1) for k in range(25)] + [round(3.6 + 0.1 * k, 1) for k in range(15)] # 3,5 закрыта vv = [round(0.6 - 0.02 * k, 2) for k in range(31)] assert len(bv) == len(vc) and len(vv) == len(hc) o = np.zeros_like(im, bool) o[y0:y1, x0:x1] = ndi.binary_opening(im[y0:y1, x0:x1] < 128, structure=np.ones((6, 6))) O = o[y0:y1] labels = [0.10, 0.12, 0.14, 0.16, 0.18, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.60, 0.70, 0.80, 0.90, 1.00, 1.25, 1.50, 2.00] pts = {l: [] for l in labels} xsplit = np.interp(1.28, bv, vc) for x in range(345, 1950): if any(a - 1 <= x <= b + 1 for a, b in vg): continue cs = centers(O, x, y0, hg) if len(cs) == len(labels) and x >= xsplit: for l, c in zip(labels, cs): pts[l].append((x, c)) left = [0.10, 0.20, 0.40, 2.00] # линии, доведённые до β = 1 (установлено по стыку при β ≈ 1,27) for x in range(int(np.interp(1.02, bv, vc)), int(np.interp(1.262, bv, vc))): if any(a - 1 <= x <= b + 1 for a, b in vg): continue cs = centers(O, x, y0, hg) if len(cs) == 4: for l, c in zip(left, cs): pts[l].append((x, c)) return table(pts, vc, bv, hc, vv, 0.550103), (vc, bv, hc, vv) def fig_K4(): im = load("p041") y0, y1, x0, x1 = 1570, 2910, 540, 1820 vg, hg = gridlines(im, y0, y1, x0, x1, frac=0.6) vc = [0.5 * (a + b) for a, b in vg] bv = [1.0] + [round(1.1 + 0.1 * k, 1) for k in range(9)] + [2.0] + [round(2.1 + 0.1 * k, 1) for k in range(9)] \ + [3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.2, 4.4, 4.6, 4.8, 5.0] assert len(bv) == len(vc) fl = [25, 20, 15, 10, 9, 8, 7, 6, 5, 4, 3, 2.5, 2, 1.5, 1] # подписанные линии сетки f fpx = [1587.5, 1688.5, 1832.5, 1966.5, 2009.5, 2063.5, 2111.5, 2168.5, 2231.5, 2345.5, 2444.5, 2520.5, 2614.5, 2734.5, 2902.5] px2f = lambda y: float(np.exp(np.interp(y, fpx, np.log(fl)))) # noqa: E731 f2px = lambda f: float(np.interp(np.log(f), np.log(fl[::-1]), fpx[::-1])) # noqa: E731 o = np.zeros_like(im, bool) o[y0:y1, x0:x1] = ndi.binary_opening(im[y0:y1, x0:x1] < 128, structure=np.ones((6, 6))) OT = o.T.copy()[x0:x1] labels = sorted(g4._FIG_K4_F["lines"]) rows = {} for y in range(1592, 2898): if any(a - 2 <= y <= b + 2 for a, b in hg): continue rows[y] = centers(OT, y, x0, vg, thick=13) pts = {l: [] for l in labels} for y in range(2700, 2898): if y in rows and len(rows[y]) == len(labels): for l, c in zip(labels, rows[y]): pts[l].append((c, y)) for l in labels: # «наращивание» линии вверх по прогнозу for ytop in range(2690, 1590, -10): A = np.array(pts[l], float) sel = A[:, 1] <= A[:, 1].min() + 250 c = np.polyfit(A[sel, 1], A[sel, 0], 2 if sel.sum() > 150 else 1) for y in range(ytop, ytop - 10, -1): if y in rows and np.polyval(c, y) <= 1798: near = [cc for cc in rows[y] if abs(cc - np.polyval(c, y)) <= 5] if len(near) == 1: pts[l].append((near[0], y)) levels = g4._FIG_K4_F["f_levels"] out = {} for l in labels: A = np.array(pts[l], float) c = np.polyfit(A[:, 1], A[:, 0], 3) row = [] for f in levels: y = f2px(f) if y < A[:, 1].min() - 25 or np.polyval(c, y) > 1806: break row.append(round(float(np.interp(np.polyval(c, y), vc, bv)), 4)) out[l] = row return out def fig_L1(): im = load("p044") y0, y1, x0, x1 = 890, 2100, 940, 1650 vcx = [1005.0, 1097.0, 1232.0, 1373.0, 1500.0, 1633.0] # σ_б1 = 120, 140, 170, 200, 230, 250 hcy = [907.0, 1089.0, 1254.0, 1426.0, 1594.0, 1776.5, 1948.5, 2081.5] Mv = [3500, 3000, 2500, 2000, 1500, 1000, 500, 100] o = ndi.binary_opening(im[y0:y1, x0:x1] < 128, structure=np.ones((7, 7))) labels = [52, 48, 42, 36, 30, 27, 24, 22, 20] pts = {l: [] for l in labels} for x in range(1010, 1628): if any(abs(x - g) < 8 for g in vcx): continue cs = [0.5 * (a + b) + y0 for a, b in runs1d(o[:, x - x0]) if b - a + 1 >= 7] if len(cs) == 9: for l, c in zip(labels, cs): pts[l].append((x, c)) elif len(cs) == 8 and x > 1400: for l, c in zip(labels[::-1], cs[::-1]): pts[l].append((x, c)) out = {} for l in labels: P = np.array(pts[l]) P = P[P[:, 1] > 912] for _ in range(6): c = np.polyfit(P[:, 0], P[:, 1], 1) res = P[:, 1] - np.polyval(c, P[:, 0]) ok = np.abs(res) <= max(3.0, 3 * np.sqrt(np.mean(res ** 2))) if ok.all(): break P = P[ok] out[l] = [round(float(np.interp(np.polyval(c, xs), hcy, Mv))) if np.polyval(c, xs) >= 907 else None for xs in vcx] return out def overlay(page, crop, fig, grid, path): vc, bv, hc, vals = grid im = Image.open(os.path.join(SCAN, page + ".png")).convert("RGB") d = ImageDraw.Draw(im) bb = np.linspace(1.0, 5.0, 600) for row in fig["val"]: v = PchipInterpolator(np.log(fig["beta"]), row)(np.log(bb)) d.line(list(zip(np.interp(bb, bv, vc), np.interp(v, vals[::-1], hc[::-1]))), fill=(255, 0, 0), width=2) im.crop(crop).save(path) def main(): out_dir = sys.argv[sys.argv.index("--overlay") + 1] if "--overlay" in sys.argv else None (labs, T2), grid2 = fig_K2() d2 = np.abs(T2 - np.array(g4._FIG_K2_BETA_F["val"])).max() print(f"рис. К.2 (β_F): {len(labs)} кривых; max |оцифровка − таблица модуля| = {d2:.4f}") (labs, T3), grid3 = fig_K3() d3 = np.abs(T3 - np.array(g4._FIG_K3_BETA_V["val"])).max() print(f"рис. К.3 (β_V): {len(labs)} кривых; max |оцифровка − таблица модуля| = {d3:.4f}") L4 = fig_K4() d4 = max(abs(a - b) for l in L4 for a, b in zip(L4[l], g4._FIG_K4_F["lines"][l])) n4 = all(len(L4[l]) == len(g4._FIG_K4_F["lines"][l]) for l in L4) print(f"рис. К.4 (f): {len(L4)} линий; max |Δβ| = {d4:.4f}; длины совпадают: {n4}") L1 = fig_L1() dl = max(abs(a - b) for l in L1 for a, b in zip(L1[l], g4._FIG_L1_MKR["M_Nm"][l]) if a is not None and b is not None) print(f"рис. Л.1 (M_кр): {len(L1)} линий; max |ΔM| = {dl} Н·м") if out_dir: os.makedirs(out_dir, exist_ok=True) overlay("p040", (420, 2070, 2100, 3000), g4._FIG_K2_BETA_F, grid2, os.path.join(out_dir, "K2_overlay.png")) overlay("p041", (320, 400, 1975, 1275), g4._FIG_K3_BETA_V, grid3, os.path.join(out_dir, "K3_overlay.png")) print(f"наложения сохранены в {out_dir}") ok = d2 < 0.002 and d3 < 0.002 and d4 < 0.002 and n4 and dl <= 1 print("ВОСПРОИЗВЕДЕНО" if ok else "РАСХОЖДЕНИЕ С ТАБЛИЦАМИ МОДУЛЯ") return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())