"""Check a brain mask against the DWI grid and report plausibility facts. Usage: python -I mask_facts.py MASK.nii.gz MEAN_B0.nii OUT.json """ import json import sys import nibabel as nb import numpy as np mask_path, b0_path, out_path = sys.argv[1:4] m = nb.load(mask_path) b = nb.load(b0_path) md = np.asarray(m.dataobj) bd = np.asarray(b.dataobj, dtype=np.float32) inside = md > 0 idx = np.argwhere(inside) lo, hi = idx.min(0), idx.max(0) vox_ml = float(np.prod(m.header.get_zooms()[:3])) / 1000.0 # Fraction of bright b0 voxels (above the 60th percentile of nonzero) inside the mask. thr = np.percentile(bd[bd > 0], 60) labels = np.unique(md).tolist() facts = { "mask": mask_path, "shape": list(md.shape), "dtype": str(m.header.get_data_dtype()), "same_shape_as_dwi_grid": md.shape == bd.shape, "affine_equal_to_dwi": bool(np.allclose(m.affine, b.affine, atol=1e-5)), "labels": labels, "voxels": int(inside.sum()), "volume_ml": round(inside.sum() * vox_ml, 1), "bbox_min_ijk": lo.tolist(), "bbox_max_ijk": hi.tolist(), "bbox_extent_mm": ((hi - lo + 1) * np.array(m.header.get_zooms()[:3])).tolist(), "touches_grid_edge": bool((lo == 0).any() or (hi == np.array(md.shape) - 1).any()), "mean_b0_inside": float(bd[inside].mean()), "mean_b0_outside": float(bd[~inside].mean()), "bright_b0_fraction_inside": float((inside & (bd > thr)).sum() / (bd > thr).sum()), } with open(out_path, "w") as f: json.dump(facts, f, indent=2) print(json.dumps(facts, indent=1))