def test_error_messages_connected_label_regions(): shape = (13, 11, 12) affine = np.eye(4) n_regions = 2 labels_img = generate_labeled_regions(shape, affine=affine, n_regions=n_regions) with pytest.raises( ValueError, match="Expected 'min_size' to be specified as integer."): connected_label_regions(labels_img=labels_img, min_size='a') with pytest.raises( ValueError, match="'connect_diag' must be specified as True or False."): connected_label_regions(labels_img=labels_img, connect_diag=None)
def nil_parcellate(func_file, clust_mask, k, clust_type, ID, dir_path, uatlas_select): import time import nibabel as nib from nilearn.regions import Parcellations from nilearn.regions import connected_label_regions detrending = True start = time.time() func_img = nib.load(func_file) mask_img = nib.load(clust_mask) clust_est = Parcellations(method=clust_type, detrend=detrending, n_parcels=int(k), mask=mask_img) clust_est.fit(func_img) region_labels = connected_label_regions(clust_est.labels_img_) nib.save(region_labels, uatlas_select) print("%s%s%s" % (clust_type, k, " clusters: %.2fs" % (time.time() - start))) return
def get_seeds(self, nifti_img_path, connect_diag=True, min_size=100): """ Get the seeds from regions in a group parcellation Nifti image :param nifti_img_path: str Path to the group parcellation Nifti image :param connect_diag: See the documentation of nilearn.regions.connected_label_regions :param min_size: See the documentation of nilearn.regions.connected_label_regions :return: l_medoids: list of tuple of shape (x,y,z) Each tuple represents the coordinates of the seed voxel of a region l_medoids_coord_mniL list of tuple of shape (x,y,z) Each tuple represents the coordinates of the seed voxel of a region in MNI coordinates """ mist_img = nb.load(nifti_img_path) regions = connected_label_regions(nifti_img_path, connect_diag=connect_diag, min_size=min_size).get_data() labels_regions = np.unique(regions) # Apply the kmedoids clustering for each region l_medoids = [] for label in range(1, len(labels_regions)): label_coords = np.argwhere(regions == label) kmedoids_instance = kmedoids(label_coords, [0]) kmedoids_instance.process() medoid = kmedoids_instance.get_medoids() elem = tuple(label_coords[medoid[0]]) l_medoids.append(elem) l_medoids_coord_mni = [coord_transform(medoid[0], medoid[1], medoid[2], mist_img.get_affine()) for medoid in l_medoids] return l_medoids, l_medoids_coord_mni
def test_connected_label_regions(): shape = (13, 11, 12) affine = np.eye(4) n_regions = 9 labels_img = generate_labeled_regions(shape, affine=affine, n_regions=n_regions) labels_data = get_data(labels_img) n_labels_wo_reg_ext = len(np.unique(labels_data)) # region extraction without specifying min_size extracted_regions_on_labels_img = connected_label_regions(labels_img) extracted_regions_labels_data = get_data(extracted_regions_on_labels_img) n_labels_wo_min = len(np.unique(extracted_regions_labels_data)) assert n_labels_wo_reg_ext < n_labels_wo_min # with specifying min_size extracted_regions_with_min = connected_label_regions(labels_img, min_size=100) extracted_regions_with_min_data = get_data(extracted_regions_with_min) n_labels_with_min = len(np.unique(extracted_regions_with_min_data)) assert n_labels_wo_min > n_labels_with_min # Test connect_diag=False ext_reg_without_connect_diag = connected_label_regions(labels_img, connect_diag=False) data_wo_connect_diag = get_data(ext_reg_without_connect_diag) n_labels_wo_connect_diag = len(np.unique(data_wo_connect_diag)) assert n_labels_wo_connect_diag > n_labels_wo_reg_ext # If min_size is large and if all the regions are removed then empty image # will be returned extract_reg_min_size_large = connected_label_regions(labels_img, min_size=500) assert np.unique(get_data(extract_reg_min_size_large)) == 0 # Test the names of the brain regions given in labels. # Test labels for 9 regions in n_regions labels = [ 'region_a', 'region_b', 'region_c', 'region_d', 'region_e', 'region_f', 'region_g', 'region_h', 'region_i' ] # If labels are provided, first return will contain extracted labels image # and second return will contain list of new names generated based on same # name with assigned on both hemispheres for example. extracted_reg, new_labels = connected_label_regions(labels_img, min_size=100, labels=labels) # The length of new_labels returned can differ depending upon min_size. If # min_size given is more small regions can be removed therefore newly # generated labels can be less than original size of labels. Or if min_size # is less then newly generated labels can be more. # We test here whether labels returned are empty or not. assert new_labels != '' assert len(new_labels) <= len(labels) # labels given in numpy array labels = np.asarray(labels) extracted_reg2, new_labels2 = connected_label_regions(labels_img, labels=labels) assert new_labels != '' # By default min_size is less, so newly generated labels can be more. assert len(new_labels2) >= len(labels) # If number of labels provided are wrong (which means less than number of # unique labels in labels_img), then we raise an error # Test whether error raises unique_labels = set(np.unique(np.asarray(get_data(labels_img)))) unique_labels.remove(0) # labels given are less than n_regions=9 provided_labels = [ 'region_a', 'region_c', 'region_f', 'region_g', 'region_h', 'region_i' ] assert len(provided_labels) < len(unique_labels) with pytest.raises(ValueError): connected_label_regions(labels_img, labels=provided_labels) # Test if unknown/negative integers are provided as labels in labels_img, # we raise an error and test the same whether error is raised. labels_data = np.zeros(shape, dtype=np.int) h0 = shape[0] // 2 h1 = shape[1] // 2 h2 = shape[2] // 2 labels_data[:h0, :h1, :h2] = 1 labels_data[:h0, :h1, h2:] = 2 labels_data[:h0, h1:, :h2] = 3 labels_data[:h0, h1:, h2:] = 4 labels_data[h0:, :h1, :h2] = 5 labels_data[h0:, :h1, h2:] = 6 labels_data[h0:, h1:, :h2] = np.nan labels_data[h0:, h1:, h2:] = np.inf neg_labels_img = nibabel.Nifti1Image(labels_data, affine) with pytest.raises(ValueError): connected_label_regions(labels_img=neg_labels_img) # If labels_img provided is 4D Nifti image, then test whether error is # raised or not. Since this function accepts only 3D image. labels_4d_data = np.zeros((shape) + (2, )) labels_data[h0:, h1:, :h2] = 0 labels_data[h0:, h1:, h2:] = 0 labels_4d_data[..., 0] = labels_data labels_4d_data[..., 1] = labels_data labels_img_4d = nibabel.Nifti1Image(labels_4d_data, np.eye(4)) with pytest.raises(DimensionError): connected_label_regions(labels_img=labels_img_4d) # Test if labels (or names to regions) given is a string without a list. # Then, we expect it to be split to regions extracted and returned as list. labels_in_str = 'region_a' labels_img_in_str = generate_labeled_regions(shape, affine=affine, n_regions=1) extract_regions, new_labels = connected_label_regions(labels_img_in_str, labels=labels_in_str) assert isinstance(new_labels, list) # If user has provided combination of labels, then function passes without # breaking and new labels are returned based upon given labels and should # be equal or more based on regions extracted combined_labels = [ 'region_a', '1', 'region_b', '2', 'region_c', '3', 'region_d', '4', 'region_e' ] ext_reg, new_labels = connected_label_regions(labels_img, labels=combined_labels) assert len(new_labels) >= len(combined_labels)
def test_connected_label_regions(): shape = (13, 11, 12) affine = np.eye(4) n_regions = 9 labels_img = testing.generate_labeled_regions(shape, affine=affine, n_regions=n_regions) labels_data = labels_img.get_data() n_labels_wo_reg_ext = len(np.unique(labels_data)) # region extraction without specifying min_size extracted_regions_on_labels_img = connected_label_regions(labels_img) extracted_regions_labels_data = extracted_regions_on_labels_img.get_data() n_labels_wo_min = len(np.unique(extracted_regions_labels_data)) assert_true(n_labels_wo_reg_ext < n_labels_wo_min) # with specifying min_size extracted_regions_with_min = connected_label_regions(labels_img, min_size=100) extracted_regions_with_min_data = extracted_regions_with_min.get_data() n_labels_with_min = len(np.unique(extracted_regions_with_min_data)) assert_true(n_labels_wo_min > n_labels_with_min) # Test connect_diag=False ext_reg_without_connect_diag = connected_label_regions(labels_img, connect_diag=False) data_wo_connect_diag = ext_reg_without_connect_diag.get_data() n_labels_wo_connect_diag = len(np.unique(data_wo_connect_diag)) assert_true(n_labels_wo_connect_diag > n_labels_wo_reg_ext) # If min_size is large and if all the regions are removed then empty image # will be returned extract_reg_min_size_large = connected_label_regions(labels_img, min_size=500) assert_true(np.unique(extract_reg_min_size_large.get_data()) == 0) # Test the names of the brain regions given in labels. # Test labels for 9 regions in n_regions labels = ['region_a', 'region_b', 'region_c', 'region_d', 'region_e', 'region_f', 'region_g', 'region_h', 'region_i'] # If labels are provided, first return will contain extracted labels image # and second return will contain list of new names generated based on same # name with assigned on both hemispheres for example. extracted_reg, new_labels = connected_label_regions(labels_img, min_size=100, labels=labels) # The length of new_labels returned can differ depending upon min_size. If # min_size given is more small regions can be removed therefore newly # generated labels can be less than original size of labels. Or if min_size # is less then newly generated labels can be more. # We test here whether labels returned are empty or not. assert_not_equal(new_labels, '') assert_true(len(new_labels) <= len(labels)) # labels given in numpy array labels = np.asarray(labels) extracted_reg2, new_labels2 = connected_label_regions(labels_img, labels=labels) assert_not_equal(new_labels, '') # By default min_size is less, so newly generated labels can be more. assert_true(len(new_labels2) >= len(labels)) # If number of labels provided are wrong (which means less than number of # unique labels in labels_img), then we raise an error # Test whether error raises unique_labels = set(np.unique(np.asarray(labels_img.get_data()))) unique_labels.remove(0) # labels given are less than n_regions=9 provided_labels = ['region_a', 'region_c', 'region_f', 'region_g', 'region_h', 'region_i'] assert_true(len(provided_labels) < len(unique_labels)) np.testing.assert_raises(ValueError, connected_label_regions, labels_img, labels=provided_labels) # Test if unknown/negative integers are provided as labels in labels_img, # we raise an error and test the same whether error is raised. labels_data = np.zeros(shape, dtype=np.int) h0 = shape[0] // 2 h1 = shape[1] // 2 h2 = shape[2] // 2 labels_data[:h0, :h1, :h2] = 1 labels_data[:h0, :h1, h2:] = 2 labels_data[:h0, h1:, :h2] = 3 labels_data[:h0, h1:, h2:] = 4 labels_data[h0:, :h1, :h2] = 5 labels_data[h0:, :h1, h2:] = 6 labels_data[h0:, h1:, :h2] = np.nan labels_data[h0:, h1:, h2:] = np.inf neg_labels_img = nibabel.Nifti1Image(labels_data, affine) np.testing.assert_raises(ValueError, connected_label_regions, labels_img=neg_labels_img) # If labels_img provided is 4D Nifti image, then test whether error is # raised or not. Since this function accepts only 3D image. labels_4d_data = np.zeros((shape) + (2, )) labels_data[h0:, h1:, :h2] = 0 labels_data[h0:, h1:, h2:] = 0 labels_4d_data[..., 0] = labels_data labels_4d_data[..., 1] = labels_data labels_img_4d = nibabel.Nifti1Image(labels_4d_data, np.eye(4)) np.testing.assert_raises(DimensionError, connected_label_regions, labels_img=labels_img_4d) # Test if labels (or names to regions) given is a string without a list. # Then, we expect it to be split to regions extracted and returned as list. labels_in_str = 'region_a' labels_img_in_str = testing.generate_labeled_regions(shape, affine=affine, n_regions=1) extract_regions, new_labels = connected_label_regions(labels_img_in_str, labels=labels_in_str) assert_true(isinstance(new_labels, list)) # If user has provided combination of labels, then function passes without # breaking and new labels are returned based upon given labels and should # be equal or more based on regions extracted combined_labels = ['region_a', '1', 'region_b', '2', 'region_c', '3', 'region_d', '4', 'region_e'] ext_reg, new_labels = connected_label_regions(labels_img, labels=combined_labels) assert_true(len(new_labels) >= len(combined_labels))
############################################################################## # The original Yeo atlas has 7 labels, that is indicated in the colorbar. # The colorbar also shows the correspondence between the color and the label # # Note that these 7 labels correspond actually to networks that comprise # several regions. We are going to split them up. ############################################################################## # Relabeling the atlas into separated regions # --------------------------------------------- # # Now we use the connected_label_regions to break appart the networks # of the Yeo atlas into separated regions from nilearn.regions import connected_label_regions region_labels = connected_label_regions(atlas_yeo) ############################################################################## # Plotting the new regions plotting.plot_roi(region_labels, title='Relabeled Yeo atlas', cut_coords=(8, -4, 9), colorbar=True, cmap='Paired') ############################################################################## # Note that the same cluster in original and labeled atlas could have # different color, so, you cannot directly compare colors. # # However, you can see that the regions in the left and right hemispheres # now have different colors. For some regions it is difficult to tell # appart visually, as the colors are too close on the colormap (eg in the # blue: regions labeled around 3). #
import matplotlib.pyplot as plt data_dir = '/tmp' # directory where you put your data lesion = os.path.join(data_dir, 'lesion.nii.gz') # here it is assumed that your input lesion image is available at # '/tmp/lesion.nii.gz' # change it to any path you like atlas = fetch_atlas_yeo_2011() thick17 = atlas['thick_17'] # optionally display the atlas # plot_roi(thick17) # separate yeo17 atlas into connected components: # 122 connected components overall separate_thick17 = connected_label_regions(thick17) # display the lesion on top of the atlas display = plot_img(lesion) display.add_overlay(thick17, cmap=plt.cm.hsv) # compute the mean of lesion proportion per network masker = NiftiLabelsMasker(labels_img=thick17).fit() network_lesion = masker.transform(lesion) # redo that on a per'region basis display = plot_img(lesion) display.add_overlay(separate_thick17, cmap=plt.cm.hsv) # compute the mean of lesion proportion per network separate_masker = NiftiLabelsMasker(labels_img=separate_thick17).fit()
############################################################################## # The original Yeo atlas has 7 labels, that is indicated in the colorbar. # The colorbar also shows the correspondence between the color and the label # # Note that these 7 labels correspond actually to networks that comprise # several regions. We are going to split them up. ############################################################################## # Relabeling the atlas into separated regions # --------------------------------------------- # # Now we use the connected_label_regions to break apart the networks # of the Yeo atlas into separated regions from nilearn.regions import connected_label_regions region_labels = connected_label_regions(atlas_yeo) ############################################################################## # Plotting the new regions plotting.plot_roi(region_labels, title='Relabeled Yeo atlas', cut_coords=(8, -4, 9), colorbar=True, cmap='Paired') ############################################################################## # Note that the same cluster in original and labeled atlas could have # different color, so, you cannot directly compare colors. # # However, you can see that the regions in the left and right hemispheres # now have different colors. For some regions it is difficult to tell