def test_deprecation_warning_compute_gray_matter_mask(): img = Nifti1Image(np.ones((9, 9, 9)), np.eye(4)) if distutils.version.LooseVersion(sklearn.__version__) < '0.22': with pytest.deprecated_call(): masking.compute_gray_matter_mask(img) else: with pytest.warns(FutureWarning, match="renamed to 'compute_brain_mask'"): masking.compute_gray_matter_mask(img)
def extract_gm_signals(self, subj_scan): if self.gm_mask is None: self.gm_mask = compute_gray_matter_mask(subj_scan, smoothing=self.smoothing, verbose=self.verbosity) gm_signals = apply_mask(subj_scan, self.gm_mask, smoothing=self.smoothing, verbose=self.verbosity) return gm_signals
def test_compute_gray_matter_mask(): image = Nifti1Image(np.ones((9, 9, 9)), np.eye(4)) mask = compute_gray_matter_mask(image, threshold=-1) mask1 = np.zeros((9, 9, 9)) mask1[2:-2, 2:-2, 2:-2] = 1 np.testing.assert_array_equal(mask1, mask.get_data()) # Check that we get a useful warning for empty masks assert_warns(masking.MaskWarning, compute_gray_matter_mask, image, threshold=1) # Check that masks obtained from same FOV are the same img1 = Nifti1Image(np.full((9, 9, 9), np.random.rand()), np.eye(4)) img2 = Nifti1Image(np.full((9, 9, 9), np.random.rand()), np.eye(4)) mask_img1 = compute_gray_matter_mask(img1) mask_img2 = compute_gray_matter_mask(img2) np.testing.assert_array_equal(mask_img1.get_data(), mask_img2.get_data())
def test_compute_gray_matter_mask(): image = Nifti1Image(np.ones((9, 9, 9)), np.eye(4)) mask = compute_gray_matter_mask(image, threshold=-1) mask1 = np.zeros((9, 9, 9)) mask1[2:-2, 2:-2, 2:-2] = 1 np.testing.assert_array_equal(mask1, get_data(mask)) # Check that we get a useful warning for empty masks with pytest.warns(masking.MaskWarning): compute_gray_matter_mask(image, threshold=1) # Check that masks obtained from same FOV are the same img1 = Nifti1Image(np.full((9, 9, 9), np.random.rand()), np.eye(4)) img2 = Nifti1Image(np.full((9, 9, 9), np.random.rand()), np.eye(4)) mask_img1 = compute_gray_matter_mask(img1) mask_img2 = compute_gray_matter_mask(img2) np.testing.assert_array_equal(get_data(mask_img1), get_data(mask_img2))
def Add_MRI(self, selectors): if selectors == "brain": masker = masking.compute_gray_matter_mask( self.gm_imgs[0] ) #computes full brain mask... misnamed function else: Atlas = ATLAS() masker = Atlas.Mask(selectors) gm = masking.apply_mask(self.gm_imgs, masker) wm = masking.apply_mask(self.wm_imgs, masker) brain = gm + wm self.masker = masker self.features = np.hstack((self.features, brain))
def nii2png(niiPath=None, imgPath=None, axis='z', cut=(0, ), blackBg='auto', mask=True, maskThresh=0.8, maskConnected=True, maskOpening=3, verbose=0): if (os.path.isfile(niiPath) and os.path.splitext[1] == '.nii'): if (os.path.isdir(os.path.dirname(imgPath)) and not os.path.isdir(imgPath) and os.path.splitext[1] == '.png'): imgMask = None brainImg = image.load_img(niiPath) if (mask): imgMask = masking.compute_gray_matter_mask( brainImg, threshold=maskThresh, connected=maskConnected, opening=maskOpening, verbose=verbose) brainImg = image.math_img('img1 * img2', img1=brainImg, img2=imgMask) if (verbose > 0): print('Outputing image at {}...'.format(imgPath)) plotting.plot_anat(anat_img=niiPath, display_mode=axis, output_file=imgPath.format(dataDir), cut_coords=cut, annotate=False, draw_cross=False, black_bg=blackBg) elif (not os.path.isdir(os.path.dirname(imgPath))): print('{} is an invalid directory!!!'.format( os.path.dirname(imgPath))) elif (os.path.isdir(imgPath)): print( '{} is a directory, not a valid file path!!!'.format(imgPath)) elif (not os.path.splitext[1] == '.png'): print('{} is not a .png file!!!'.format(os.path.split(imgPath)[1])) elif (not os.path.isfile(niiPath)): print('{} is not a valid path!!!'.format(niiPath)) elif (not os.path.splitext(niiPath)[1] == '.nii'): print('{} is not a .nii file!!!'.format(os.path.split(niiPath)[1]))
def get2Dskeleton(img=None, axis='z', sliceIndex=0, lowThresh=0.21, highThresh=0.27, mask=True, verbose=0): """ Gets the 2D skeleton of an image imgPath -> relative or absolute path to a .png image lowThresh (optional, default=0.21) -> float between 0 and 1 - low threshold for the hysteresis filter highThresh (optional, default=0.27) -> float between 0 and 1 - high threshold for the hysteresis filter crop (optional, default=(15, 143, 30, 158)) -> (x1, x2, y1, y2) Tuple containing the crop coordinates !!! lowThresh must be lower than highThresh verbose (optional, default=0) -> int - the higher it is, the more messages will be outputted to the console """ img = image.load_img(img) if (mask): imgMask = masking.compute_gray_matter_mask(img, verbose=verbose) img = image.math_img('img1 * img2', img1=img, img2=imgMask) img = img.get_fdata() if (axis == 'y'): img = img[sliceIndex] elif (axis == 'x'): img = img[:, sliceIndex, :] elif (axis == 'z'): img = img[:, :, sliceIndex] if (verbose > 0): print('Applying hysterisis filter...\n') # Binarize the image with a hysteresis filter res = filters.apply_hysteresis_threshold(img, lowThresh, highThresh) # Get the largest connected component of the image if (verbose > 2): plotComparison(img, res, 'Original', 'L = ' + str(lowThresh) + " R = " + str(highThresh)) # Skeletonize the image res = morphology.skeletonize(res) res = getLargestCC(res) res = res.astype(int) #print("Minkowski–Bouligand dimension: ", dimension) if (verbose > 1): print('Filtered image:') plotComparison(img, res, 'Original', 'Skeletonized') return res
def get3Dskeleton(imgPath=None, thresh='30%', mask=True, verbose=0): """ Gets the 3D skeleton of an image imgPath -> Relative or absolute path to a .nii image or nii variable thresh (optional, default='30%') -> Threshold value. Either float or string like 'x.xx%' mask (optional, default=True) -> Applies a gray matter mask if true verbose (optional, default=0) -> int - the higher it is, the more messages will be outputted to the console Returns a Nifti1Image object containing the skeletonized image """ brain = image.load_img(imgPath) if (mask): imgMask = masking.compute_gray_matter_mask(target_img=brain, threshold=0.3, connected=True, opening=1) brain = image.math_img('img1 * img2', img1=brain, img2=imgMask) brain = image.threshold_img(brain, thresh) affine = brain.affine data = brain.get_data() data = data / np.amax(data) #data = filters.threshold_adaptive(data, 35, 10) skeleton = morphology.skeletonize_3d(data) skeletonBrain = nifti.Nifti1Image(skeleton, affine) return skeletonBrain
"""Extract coordinates from images.""" import nilearn from nilearn import image, masking from nipy.labs.statistical_mapping import get_3d_peaks from data_utils import iterator_imgs, retrieve_imgs template = nilearn.datasets.load_mni152_template() gray_mask = masking.compute_gray_matter_mask(template) def get_activations_one_img(img, threshold, verbose=False): """ Retrieve the xyz activation coordinates from an image. Args: img (Nifti1Image): Nifti1Image from which to extract coordinates. threshold (float): value below threshold are ignored. Used for peak detection. Returns: (tuple): Size 3 tuple of lists storing respectively the X, Y and Z coordinates. """ if verbose: print('Extracting') X, Y, Z = [], [], [] img = image.resample_to_img(img, template)
def nii2csv(niiPath=None, csvPath=None, axis='z', cut=(0, ), blackBg='auto', mask=1, maskThresh=0.5, maskConnected=True, maskOpening=3, verbose=0): """ Takes a .nii file and converts it to a .csv file containing a 3D grayscale array Arguments: niiPath -> the .nii filepath (relative or absolute) csvPath -> the filepath of the output image (must end in .png) axis (optional, default='z') -> 'xyz' 'xy' 'xz' 'yz' 'x' 'y' 'z' - determines the axis along which the cuts are made cut (optional, default=(0,)) -> list of tuples of 1, 2 or 3 integers - determines the x, y, z position along which the cuts are made blackBg (optional, default='auto') mask (optional, default=1) -> int between 0 and 3 - determines the ammount of times a gray matter mask will be applied maskThresh (optional, default=0.8) -> float between 0 and 1 - determines the threshold used for the gray matter mask maskConnected (optional, default=True) -> bool - determines if the mask will keep only the largest connected components maskOpening (optional, default=3) -> int - number of erosions for the morphological opening verbose (optional, default=0) -> int - the higher it is, the more messages will be outputted to the console """ # Checks if the input filepath exists and has a .nii extension if (os.path.isfile(niiPath) and os.path.splitext(niiPath)[1] == '.nii'): # Checks if the output filepath's directory is valid, if it is not a directory itself and if it has a .png extension if (os.path.isdir(os.path.dirname(csvPath)) and not os.path.isdir(csvPath) and os.path.splitext(csvPath)[1] == '.png'): imgMask = None brainImg = image.load_img(niiPath) # Clamps mask between 0 and 3 mask = min(3, max(0, mask)) # Applies the mask for i in range(0, mask): imgMask = masking.compute_gray_matter_mask( brainImg, threshold=maskThresh, connected=maskConnected, opening=maskOpening, verbose=verbose) brainImg = image.math_img('img1 * img2', img1=brainImg, img2=imgMask) if (verbose > 0): print('Outputing image at {}...'.format(csvPath)) plotting.plot_anat(anat_img=brainImg, display_mode=axis, output_file=csvPath, cut_coords=cut, annotate=False, draw_cross=False, black_bg=blackBg) elif (not os.path.isdir(os.path.dirname(csvPath))): print('{} is an invalid directory!!!'.format( os.path.dirname(csvPath))) elif (os.path.isdir(csvPath)): print( '{} is a directory, not a valid file path!!!'.format(csvPath)) elif (not os.path.splitext(csvPath)[1] == '.png'): print('{} is not a .png file!!!'.format(os.path.split(csvPath)[1])) elif (not os.path.isfile(niiPath)): print('{} is not a valid path!!!'.format(niiPath)) elif (not os.path.splitext(niiPath)[1] == '.nii'): print('{} is not a .nii file!!!'.format(os.path.split(niiPath)[1]))