Download ecglib/nets.py from pashaalex/ecg-rectifier: direct link, hf CLI and curl.
- Browser
- Download file 6.26 kB
-
https://huggingface.co/pashaalex/ecg-rectifier/resolve/main/ecglib/nets.py
- Command line
-
hf download hf://pashaalex/ecg-rectifier/ecglib/nets.py
-
curl -L -o nets.py https://huggingface.co/pashaalex/ecg-rectifier/resolve/main/ecglib/nets.py
6.26 kB
| """The four ONNX networks, one function each. All run on CPU with onnxruntime. | |
| mask_net mask.onnx coarse "ECG signal / background" mask of the whole photo | |
| detector_net detector.onnx intersections of the bold 5 mm grid lines | |
| rectify_net offsets.onnx per 224 x 224 window: sheet position (mm) of its 7 x 7 patch centres | |
| lattice_gnn lattice.onnx graph network: lattice indices (i, j) of the detected nodes | |
| The detector and the offsets network expect photos at about 5.5 px/mm. | |
| """ | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| import cv2 | |
| import numpy as np | |
| import onnxruntime as ort | |
| from . import lattice | |
| from .windows import crop_image | |
| MODELS_DIR = Path(__file__).resolve().parent.parent / "models" | |
| MODEL_FILES = {"mask": "mask.onnx", "detector": "detector.onnx", "rectify": "offsets.onnx", "lattice": "lattice.onnx"} | |
| DETECTOR_THRESHOLD = 0.5 | |
| class Models: | |
| mask: ort.InferenceSession | |
| detector: ort.InferenceSession | |
| rectify: ort.InferenceSession | |
| lattice: ort.InferenceSession | |
| def _session(path, threads): | |
| options = ort.SessionOptions() | |
| options.intra_op_num_threads = threads | |
| options.inter_op_num_threads = 1 | |
| return ort.InferenceSession(str(path), options, providers=["CPUExecutionProvider"]) | |
| def load_models(models_dir=MODELS_DIR, threads=2): | |
| models_dir = Path(models_dir) | |
| return Models(**{name: _session(models_dir / file, threads) for name, file in MODEL_FILES.items()}) | |
| MASK_SIZE = 448 | |
| MASK_PAD = 128 | |
| MASK_MEAN = np.array([0.485, 0.456, 0.406], np.float32) * 255 | |
| MASK_STD = np.array([0.229, 0.224, 0.225], np.float32) * 255 | |
| def mask_net(models, photo): | |
| """Per-pixel probability of "ECG signal here" (float32, photo size). | |
| The photo is letterboxed into 448 x 448; the network predicts 56 x 56 cells.""" | |
| h, w = photo.shape[:2] | |
| s = MASK_SIZE / max(h, w) | |
| nw, nh = max(1, round(w * s)), max(1, round(h * s)) | |
| x0, y0 = (MASK_SIZE - nw) // 2, (MASK_SIZE - nh) // 2 | |
| box = np.full((MASK_SIZE, MASK_SIZE, 3), MASK_PAD, np.uint8) | |
| box[y0:y0 + nh, x0:x0 + nw] = cv2.resize(photo, (nw, nh), interpolation=cv2.INTER_AREA) | |
| x = (cv2.cvtColor(box, cv2.COLOR_BGR2RGB).astype(np.float32) - MASK_MEAN) / MASK_STD | |
| logits = models.mask.run(None, {"images": np.ascontiguousarray(x.transpose(2, 0, 1)[None])})[0][0] | |
| prob = 1 / (1 + np.exp(-logits)) | |
| full = cv2.resize(prob, (MASK_SIZE, MASK_SIZE), interpolation=cv2.INTER_LINEAR)[y0:y0 + nh, x0:x0 + nw] | |
| return cv2.resize(full, (w, h), interpolation=cv2.INTER_LINEAR) | |
| CROP = 224 | |
| CELL = 8 | |
| CELLS = CROP // CELL | |
| STRIDE = 56 | |
| BATCH = 32 | |
| PAD_VALUE = (128, 128, 128) | |
| def _window_weight(): | |
| c = (np.arange(CELLS) + 0.5) / CELLS | |
| w = np.sin(np.pi * c) ** 2 + 0.05 | |
| return np.outer(w, w).astype(np.float32) | |
| def detector_net(models, image, threshold=DETECTOR_THRESHOLD): | |
| """Bold-line intersections in a BGR image at ~5.5 px/mm. -> [K, 3]: x, y (px), confidence. | |
| Sliding 224 px windows (stride 56); per 8 x 8 cell the network gives a node logit and the | |
| position inside the cell. Overlapping windows are averaged with a centre-weighted window; | |
| nodes are 3 x 3 local maxima above the threshold.""" | |
| h, w = image.shape[:2] | |
| out_h = max(CROP, int(np.ceil((h - CROP) / STRIDE)) * STRIDE + CROP) | |
| out_w = max(CROP, int(np.ceil((w - CROP) / STRIDE)) * STRIDE + CROP) | |
| padded = cv2.copyMakeBorder(image, 0, out_h - h, 0, out_w - w, cv2.BORDER_CONSTANT, value=PAD_VALUE) | |
| rgb = cv2.cvtColor(padded, cv2.COLOR_BGR2RGB) | |
| ch, cw = out_h // CELL, out_w // CELL | |
| heat = np.zeros((ch, cw), np.float32) | |
| offsets = np.zeros((ch, cw, 2), np.float32) | |
| weights = np.zeros((ch, cw), np.float32) | |
| weight = _window_weight() | |
| corners = [(y, x) for y in range(0, out_h - CROP + 1, STRIDE) for x in range(0, out_w - CROP + 1, STRIDE)] | |
| for start in range(0, len(corners), BATCH): | |
| chunk = corners[start:start + BATCH] | |
| batch = np.stack([rgb[y:y + CROP, x:x + CROP] for y, x in chunk]).transpose(0, 3, 1, 2) | |
| raw = models.detector.run(None, {"images": np.ascontiguousarray(batch, dtype=np.float32)})[0] | |
| prob = 1 / (1 + np.exp(-raw[..., 0])) | |
| off = 1 / (1 + np.exp(-raw[..., 1:3])) | |
| for (y, x), p, o in zip(chunk, prob, off): | |
| cy, cx = y // CELL, x // CELL | |
| heat[cy:cy + CELLS, cx:cx + CELLS] += p * weight | |
| offsets[cy:cy + CELLS, cx:cx + CELLS] += o * weight[..., None] | |
| weights[cy:cy + CELLS, cx:cx + CELLS] += weight | |
| heat /= weights | |
| offsets /= weights[..., None] | |
| padded_heat = np.pad(heat, 1, constant_values=-1.0) | |
| neighbours = np.max(np.stack([padded_heat[dy:dy + ch, dx:dx + cw] for dy in range(3) for dx in range(3)]), axis=0) | |
| ys, xs = np.nonzero((heat >= neighbours) & (heat >= threshold)) | |
| px = (xs + offsets[ys, xs, 0]) * CELL - 0.5 | |
| py = (ys + offsets[ys, xs, 1]) * CELL - 0.5 | |
| keep = (px < w - 0.5) & (py < h - 0.5) | |
| return np.stack([px, py, heat[ys, xs]], axis=1)[keep] | |
| RECTIFY_UNIT_MM = 32.0 | |
| def rectify_net(models, image, windows, batch=16): | |
| """Offsets network for windows (x0, y0, s) of an image at ~5.5 px/mm. | |
| -> [windows, 7, 7, 2]: sheet offset (mm) of each patch centre from the central patch.""" | |
| out = [] | |
| for start in range(0, len(windows), batch): | |
| part = [crop_image(image, w) for w in windows[start:start + batch]] | |
| rgb = np.stack([cv2.cvtColor(c, cv2.COLOR_BGR2RGB).transpose(2, 0, 1) for c in part]).astype(np.float32) | |
| out.append(models.rectify.run(None, {"images": rgb})[0] * RECTIFY_UNIT_MM) | |
| return np.concatenate(out) | |
| def lattice_gnn(models, points): | |
| """Lattice indices of detector points [N, 2] (px). | |
| -> ij [N, 2] (i grows right, j down; -1 for rejected points), component [N] (-1 for rejected). | |
| Coordinates are normalised by the median nearest-neighbour distance before the network.""" | |
| xy = np.asarray(points, np.float64) | |
| c = xy - np.median(xy, 0) | |
| if len(xy) >= 2: | |
| c = c / float(np.median(lattice.nearest_distances(c))) | |
| p_real, edge_prob, idx, valid = models.lattice.run(None, {"pos": c[None].astype(np.float32)}) | |
| return lattice.assemble_gnn(p_real[0], edge_prob[0], idx[0].astype(int), valid[0].astype(bool)) | |