"""Masked-ness score by source and derivative zero count ratio for images.""" import numpy as np import nibabel as nb INPUT = "/path/to/image.nii.gz" # ============================================================================= def maskedness_score(img): """Compute a number that relates to likelihood of an image being masked. The natural range of mask score is between 0 and 1. Closer to 1 indicates the image might have been masked. More masked voxels (aka larger maskes) leads to scores closer to 1. """ # Compute spatial gradient gra = np.asarray(np.gradient(img)) gra = np.sum(np.abs(gra), axis=0) # Mask score is a ratio between an image and its derivative's zero voxels count1 = np.sum(img == 0) count2 = np.sum(gra == 0) score = count2 / count1 return score # Load data nii = nb.load(INPUT) img = nii.get_fdata() dims = img.shape # Compute mask score for the input image score1 = maskedness_score(img) # Simulate 'not defaced data' by shuffling voxels img = img.flatten() np.random.shuffle(img) img = img.reshape(dims) score2 = maskedness_score(img) print("Maskedness score = {:.3f}".format(score1)) print("Maskedness score after voxel shuffling = {:.3f}".format(score2)) print("(Shuffling is done to simulate non-masked images)".format(score2))