"""Dice between QSIPrep's SHORELine registration mask and the MindGrab mask (M0, info). The QSIPrep mask is on the LPS-reoriented DWI grid; the MindGrab mask is on the raw RAS grid. The QSIPrep mask is resampled to the MindGrab grid with nearest neighbour. Usage: python -I mask_dice.py QSIPREP_MASK MINDGRAB_MASK """ import json import sys import nibabel as nb import numpy as np from scipy.ndimage import map_coordinates def main(qsi_path: str, mg_path: str) -> None: qsi = nb.load(qsi_path) mg = nb.load(mg_path) mg_data = np.asanyarray(mg.dataobj) > 0 ijk = np.indices(mg.shape[:3]).reshape(3, -1).T world = nb.affines.apply_affine(mg.affine, ijk) qijk = nb.affines.apply_affine(np.linalg.inv(qsi.affine), world) qdata = (np.asanyarray(qsi.dataobj) > 0).astype(np.uint8) res = map_coordinates(qdata, qijk.T, order=0, mode="constant", cval=0) res = res.reshape(mg.shape[:3]) > 0 inter = int((res & mg_data).sum()) out = { "qsiprep_mask": qsi_path, "qsiprep_axcodes": "".join(nb.aff2axcodes(qsi.affine)), "qsiprep_shape": list(qsi.shape), "qsiprep_voxels": int(qdata.sum()), "mindgrab_voxels": int(mg_data.sum()), "qsiprep_voxels_on_mindgrab_grid": int(res.sum()), "dice": 2 * inter / (int(res.sum()) + int(mg_data.sum())), "qsiprep_only": int((res & ~mg_data).sum()), "mindgrab_only": int((~res & mg_data).sum()), } print(json.dumps(out, indent=1)) if __name__ == "__main__": main(sys.argv[1], sys.argv[2])