Last active
September 30, 2020 05:42
-
-
Save ofgulban/5ce784d808187b02c5c7714ef5538579 to your computer and use it in GitHub Desktop.
A simple score that might be useful to detect masked nifti files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment