#!/usr/bin/env python3 """Produce the released images from the raw ultrasound machine exports. Everything outside the acoustic sector is discarded. On this machine that region carries the vendor and hospital logos, the acquisition date and clock time, the operator-entered session code, the imaging preset and probe settings, the depth scale, the frame-rate readout, and the operator's on-screen annotation of gastric state and body position. Removing the lot in one step is both the de-identification and the removal of the on-screen text naming the state and position of each acquisition. `sector_mask.png` is the sector at the native 1200x932 export resolution: a 63-degree annular sector with its virtual apex just above the top of the frame (fitted centre 608.1, -15.0), an inner radius of 221 pixels at the probe face, an outer radius trimmed by 16 pixels, and each straight edge drawn in by 1.2 degrees. The edge insets matter: the depth-marker ticks and the frame-rate readout sit within about two degrees of the true sector edge, so the outermost sliver of the fan is given up in order to exclude them. No pixel that is bright in every frame -- that is, no machine annotation -- survives inside the mask. Output is cropped to the sector bounding box plus a 10-pixel border, rounded up to even dimensions so the cine loops can be encoded in yuv420p: 934x766. Pixels outside the sector are set to black rather than to a fill value, so that the mask remains exactly recoverable; `sector_mask_cropped.png` matches the released frames pixel for pixel. Stills are written as lossless PNG. Cine loops must be re-encoded, since the mask has to be applied to the pixels; this is done once, direct from the machine export, at H.264 CRF 14. Container metadata is discarded, which also removes the MP4 creation_time tag carrying the acquisition date. Usage: python build_release.py """ import os import subprocess import sys import cv2 import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) MASK_FULL = os.path.join(HERE, "sector_mask.png") MASK_CROP = os.path.join(HERE, "sector_mask_cropped.png") BORDER = 10 CRF, PRESET = "14", "slow" def crop_box(mask): ys, xs = np.where(mask) y0, y1 = max(ys.min() - BORDER, 0), min(ys.max() + BORDER + 1, mask.shape[0]) x0, x1 = max(xs.min() - BORDER, 0), min(xs.max() + BORDER + 1, mask.shape[1]) if (x1 - x0) % 2: x1 += 1 if (y1 - y0) % 2: y1 += 1 return y0, y1, x0, x1 def build_still(src, dst, mask, box): img = cv2.imread(src, cv2.IMREAD_COLOR) if img is None or img.shape[:2] != mask.shape: raise RuntimeError(f"unexpected image {src}") img[~mask] = 0 y0, y1, x0, x1 = box cv2.imwrite(dst, img[y0:y1, x0:x1], [cv2.IMWRITE_PNG_COMPRESSION, 9]) def build_cine(src, dst, box): y0, y1, x0, x1 = box chain = (f"[0:v]crop={x1 - x0}:{y1 - y0}:{x0}:{y0},format=gbrp[v];" f"[1:v]format=gbrp[m];" f"[v][m]blend=all_mode=multiply:shortest=1,format=yuv420p[o]") subprocess.run( ["ffmpeg", "-v", "error", "-y", "-i", src, "-loop", "1", "-i", MASK_CROP, "-filter_complex", chain, "-map", "[o]", "-c:v", "libx264", "-crf", CRF, "-preset", PRESET, "-fps_mode", "passthrough", "-an", "-map_metadata", "-1", "-movflags", "+faststart", dst], check=True, ) def main(in_root, out_root): mask = cv2.imread(MASK_FULL, cv2.IMREAD_GRAYSCALE) > 0 box = crop_box(mask) n = 0 for subject in sorted(os.listdir(in_root)): sdir = os.path.join(in_root, subject) if not os.path.isdir(sdir): continue # machine export directories are named _ID__; released ones are , lowercase name = subject.strip("_")[3:] if subject.startswith("_ID_") else subject name = name.lower() # released names are lowercase odir = os.path.join(out_root, name) os.makedirs(odir, exist_ok=True) for fn in sorted(os.listdir(sdir)): stem, ext = os.path.splitext(fn) stem = (stem[:-4] if stem.endswith("_RAW") else stem).lower() src = os.path.join(sdir, fn) if ext.lower() == ".bmp": build_still(src, os.path.join(odir, stem + ".png"), mask, box) elif ext.lower() == ".mp4": build_cine(src, os.path.join(odir, stem + ".mp4"), box) else: continue n += 1 if n % 60 == 0: print(f" {n} files", flush=True) print(f"built {n} files at {box[3] - box[2]}x{box[1] - box[0]}") if __name__ == "__main__": main(sys.argv[1], sys.argv[2])