コード例 #1
0
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)

    peaks = get_3d_peaks(img, mask=gray_mask, threshold=threshold)

    if not peaks:
        return X, Y, Z

    for peak in peaks:
        X.append(peak['pos'][0])
        Y.append(peak['pos'][1])
        Z.append(peak['pos'][2])

    del peaks
    return X, Y, Z
コード例 #2
0
ファイル: extract.py プロジェクト: alexprz/meta_ALE
def get_activations(path, threshold):
    """
    Retrieve the xyz activation coordinates from an image.

    Args:
        path (string or Nifti1Image): Path to or object of a
            nibabel.Nifti1Image from which to extract coordinates.
        threshold (float): Same as the extract_from_paths function.

    Returns:
        (tuple): Size 3 tuple of lists storing respectively the X, Y and
            Z coordinates

    """
    X, Y, Z = [], [], []

    try:
        img = nilearn.image.load_img(path)
    except ValueError:  # File path not found
        print(f'File {path} not found. Ignored.')
        return None

    if np.isnan(img.get_fdata()).any():
        print(f'Img {path} contains Nan. Ignored.')
        return None

    img = image.resample_to_img(img, template)

    peaks = get_3d_peaks(img, mask=gray_mask, threshold=threshold)

    if not peaks:
        return X, Y, Z

    for peak in peaks:
        X.append(peak['pos'][0])
        Y.append(peak['pos'][1])
        Z.append(peak['pos'][2])

    del peaks
    return X, Y, Z
コード例 #3
0
def compute_labelled_mask_from_HO_and_merged_thr_spm_mask():
    
    
    write_dir = os.path.join(nipype_analyses_path,peak_activation_mask_analysis_name)
    
    print spm_contrasts_path
    
    if not os.path.exists(write_dir):
        os.makedirs(write_dir)

       
    spm_contrast_indexes = [3,4,5,8,9,10]
    
    spm_mask_files =  [os.path.join(spm_contrasts_path,"_contrast_index_"+str(index)+"_group_contrast_index_0/spmT_0001_thr.img") for index in spm_contrast_indexes]
        
    #spm_mask_files.sort()
    
    print len(spm_mask_files)
    
    # prepare the data
    img = nib.load(spm_mask_files[0])
    
    img_header = img.get_header()
    img_affine = img.get_affine()
    img_shape = img.shape
    
    img_data = img.get_data()
    
    ########################## Computing combined HO areas 
    
    resliced_full_HO_data,HO_labels,HO_abbrev_labels = compute_recombined_HO_template(img_header,img_affine,img_shape)
    
    ########################## Creating peak activation mask contrained by HO areas 
    
    #print len(HO_abbrev_labels)
    #print len(HO_labels)
    
    #0/0
    np_HO_abbrev_labels = np.array(HO_abbrev_labels,dtype = 'string')
    
    np_HO_labels = np.array(HO_labels,dtype = 'string')
    
    template_indexes = np.unique(resliced_full_HO_data)[1:]
    
    #print template_indexes
        
    print np_HO_labels.shape,np_HO_abbrev_labels.shape,template_indexes.shape
    
    #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),np_full_label_rois,np_label_rois,rois_MNI_coords))
    #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),rois_MNI_coords))
    info_template = np.hstack((template_indexes.reshape(len(HO_labels),1),np_HO_labels.reshape(len(HO_labels),1),np_HO_abbrev_labels.reshape(len(HO_labels),1)))
    #,rois_MNI_coords))
    
    print info_template
   
    np.savetxt(info_template_file,info_template, fmt = '%s %s %s')
    
    #np.savetxt(info_template_file,info_rois, fmt = '%s %s %s %s %s %s')
      
      
      
      
    
    
    merged_mask_data = np.zeros(shape = img_shape,dtype = float)
    
    print merged_mask_data.shape
    
    list_orig_ROI_spm_index = []
    
    ### list for all info about peaks after merging between different contrasts
    list_orig_peak_coords = []
    list_orig_peak_MNI_coords = []
    list_orig_peak_vals = []
    
    for i,spm_mask_file in enumerate(spm_mask_files):
        
        print spm_mask_file
        
        spm_mask_img = nib.load(spm_mask_file)
        
        spm_mask_data = spm_mask_img.get_data()

        #### get peaks (avec la fonction stat_map.get_3d_peaks)
        peaks =  stat_map.get_3d_peaks(image=spm_mask_img,mask=None)
        
        #print len(peaks)
        
        if peaks != None :
                
            print len(peaks)
            list_orig_peak_vals = list_orig_peak_vals + [peak['val'] for peak in peaks]
            list_orig_peak_coords = list_orig_peak_coords + [peak['ijk'] for peak in peaks]
            list_orig_peak_MNI_coords = list_orig_peak_MNI_coords + [peak['pos'] for peak in peaks]
        
            #print list_orig_peak_vals
        
            #print np.where(np.isnan(spm_mask_data))
            
            #print spm_mask_data[]
            
            #merged_mask_data[np.logical_and(spm_mask_data != 0.0, np.logical_not(np.isnan(spm_mask_data)))] = 1.0
            
            merged_mask_data[np.logical_and(spm_mask_data != 0.0, np.logical_not(np.isnan(spm_mask_data)))] += i+1
            
            #print np.sum(np.logical_and(merged_mask_data != 0.0, np.logical_not(np.isnan(merged_mask_data))))
        
            list_orig_ROI_spm_index = list_orig_ROI_spm_index +  [i+1] * len(peaks)
            
        print len(list_orig_peak_coords)
        print len(list_orig_ROI_spm_index)
    
    #### selectionne les pics sur leur distance entre eux et sur leur appatenance au template HO
    
    list_selected_peaks_coords,indexed_mask_rois_data,list_selected_peaks_indexes = remove_close_peaks_neigh_in_binary_template(list_orig_peak_coords,resliced_full_HO_data,min_dist_between_ROIs)
    #list_selected_peaks_coords,indexed_mask_rois_data,list_selected_peaks_indexes = remove_close_peaks_neigh_in_binary_template(sorded_merged_peaks_coords,resliced_full_HO_data,min_dist_between_ROIs)
    
    
    nib.save(nib.Nifti1Image(data = merged_mask_data,header = img_header,affine = img_affine),merged_mask_img_file)

    print list_selected_peaks_indexes
    print len(list_selected_peaks_indexes)
    
    #for coord in list_selected_peaks_coords:
    
        #print coord
    ##template_indexes = 
        #print resliced_full_HO_data[coord[0],coord[1],coord[2]]
    
    template_indexes = np.array([resliced_full_HO_data[coord[0],coord[1],coord[2]] for coord in list_selected_peaks_coords],dtype = 'int64')
    print template_indexes
    
    np_HO_abbrev_labels = np.array(HO_abbrev_labels,dtype = 'string')
    
    np_HO_labels = np.array(HO_labels,dtype = 'string')
    
    
    print template_indexes-1
    
    label_rois = np_HO_abbrev_labels[template_indexes-1]
    full_label_rois = np_HO_labels[template_indexes-1]
    
    #print label_rois2
    
    print label_rois
    
    #### exporting Rois image with different indexes 
    print np.unique(indexed_mask_rois_data)[1:].shape
    nib.save(nib.Nifti1Image(data = indexed_mask_rois_data,header = img_header,affine = img_affine),indexed_mask_rois_file)
    
    #### saving ROI coords as textfile
    np.savetxt(coord_rois_file,np.array(list_selected_peaks_coords,dtype = int), fmt = '%d')
    
    #### saving MNI coords as textfile
    list_rois_MNI_coords = [list_orig_peak_MNI_coords[index] for index in list_selected_peaks_indexes]
    
    print list_rois_MNI_coords
    
    rois_MNI_coords = np.array(list_rois_MNI_coords,dtype = int)
    np.savetxt(MNI_coord_rois_file,rois_MNI_coords, fmt = '%d')
    
    ### orig index of peaks
    list_rois_orig_indexes = [list_orig_ROI_spm_index[index] for index in list_selected_peaks_indexes]
    
    print list_rois_orig_indexes
    
    rois_orig_indexes = np.array(list_rois_orig_indexes,dtype = int).reshape(len(list_rois_orig_indexes),1)
    
    print rois_orig_indexes.shape
    
    np.savetxt(rois_orig_indexes_file,rois_orig_indexes, fmt = '%d')
    
    
    
    #### mask with orig spm index
    orig_spm_index_mask_data = np.zeros(shape = img_shape,dtype = int)
    
    print np.unique(indexed_mask_rois_data)
    
    for i in np.unique(indexed_mask_rois_data)[1:]:
    
        print i,np.sum(indexed_mask_rois_data == i),rois_orig_indexes[i]
        
        orig_spm_index_mask_data[indexed_mask_rois_data == i] = rois_orig_indexes[i]
    
    nib.save(nib.Nifti1Image(data = orig_spm_index_mask_data,header = img_header,affine = img_affine),orig_spm_index_mask_file)
    
    #### saving labels 
    np.savetxt(label_rois_file,label_rois, fmt = '%s')
    
    ### saving all together for infosource
    np_label_rois = np.array(label_rois,dtype = 'string').reshape(len(label_rois),1)
    np_full_label_rois = np.array(full_label_rois,dtype = 'string').reshape(len(full_label_rois),1)
    
    print np_label_rois.shape
    print rois_MNI_coords.shape
    
    #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),np_full_label_rois,np_label_rois,rois_MNI_coords))
    #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),rois_MNI_coords))
    info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),np_full_label_rois,np_label_rois,rois_MNI_coords,rois_orig_indexes))
    
    print info_rois
   
    np.savetxt(info_rois_file,info_rois, fmt = '%s %s %s %s %s %s %s')
    
    
    return indexed_mask_rois_file,coord_rois_file
コード例 #4
0
def compute_labelled_mask_from_HO_all_signif_contrasts():
    
    
    write_dir = os.path.join(nipype_analyses_path,peak_activation_mask_analysis_name)
    
    print spm_contrasts_path
    
    if not os.path.exists(write_dir):
        os.makedirs(write_dir)

    #spm_mask_files =  glob.glob(os.path.join(spm_contrasts_path,rel_spm_mask_path,"_contrast_index_[1-6]_group_contrast_index_0/spmT_*.img"))
    spm_mask_files =  glob.glob(os.path.join(spm_contrasts_path,contrast_pattern))
    
    
    print spm_mask_files
    
    print spm_mask_files.sort()
    
    # prepare the data
    img = nib.load(spm_mask_files[0])
    
    img_header = img.get_header()
    img_affine = img.get_affine()
    img_shape = img.shape
    
    img_data = img.get_data()
    
    ########################## Computing combined HO areas 
    
    resliced_full_HO_data,HO_labels,HO_abbrev_labels = compute_recombined_HO_template(img_header,img_affine,img_shape)
    
    ########################## Creating peak activation mask contrained by HO areas 
    
    #print len(HO_abbrev_labels)
    #print len(HO_labels)
    
    #0/0
    np_HO_abbrev_labels = np.array(HO_abbrev_labels,dtype = 'string')
    
    np_HO_labels = np.array(HO_labels,dtype = 'string')
    
    template_indexes = np.unique(resliced_full_HO_data)[1:]
    
    #print template_indexes
        
    print np_HO_labels.shape,np_HO_abbrev_labels.shape,template_indexes.shape
    
    #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),np_full_label_rois,np_label_rois,rois_MNI_coords))
    #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),rois_MNI_coords))
    info_template = np.hstack((template_indexes.reshape(len(HO_labels),1),np_HO_labels.reshape(len(HO_labels),1),np_HO_abbrev_labels.reshape(len(HO_labels),1)))
    #,rois_MNI_coords))
    
    print info_template
   
    np.savetxt(info_template_file,info_template, fmt = '%s %s %s')
    
    #np.savetxt(info_template_file,info_rois, fmt = '%s %s %s %s %s %s')
      
    indexed_mask_rois_files = []
    
    coord_rois_files = []
    
    for i,spm_mask_file in enumerate(spm_mask_files):
        
        print spm_mask_file
        
        spm_mask_img = nib.load(spm_mask_file)
        
        spm_mask_data = spm_mask_img.get_data()

        #### get peaks (avec la fonction stat_map.get_3d_peaks)
        peaks =  stat_map.get_3d_peaks(image=spm_mask_img,mask=None, threshold = threshold,nn = cluster_nbvoxels)
        
        #print len(peaks)
        
        list_orig_ROI_spm_index = []
        
        if peaks != None :
                
            print len(peaks)
            list_orig_peak_vals = [peak['val'] for peak in peaks]
            list_orig_peak_coords = [peak['ijk'] for peak in peaks]
            list_orig_peak_MNI_coords = [peak['pos'] for peak in peaks]
        
            merged_mask_data = spm_mask_data[np.logical_and(spm_mask_data != 0.0, np.logical_not(np.isnan(spm_mask_data)))]
            
            list_orig_ROI_spm_index = list_orig_ROI_spm_index +  [i+1] * len(peaks)
                
            print len(list_orig_peak_coords)
            print len(list_orig_ROI_spm_index)
        
            
            list_selected_peaks_coords,indexed_mask_rois_data,list_selected_peaks_indexes = remove_close_peaks_neigh_in_binary_template(list_orig_peak_coords,resliced_full_HO_data,min_dist_between_ROIs)
            
            print list_selected_peaks_indexes
            print len(list_selected_peaks_indexes)
            
            
            merged_mask_data[indexed_mask_rois_data != 0] += i+1 
            
            template_indexes = np.array([resliced_full_HO_data[coord[0],coord[1],coord[2]] for coord in list_selected_peaks_coords],dtype = 'int64')
            print template_indexes
            
            np_HO_abbrev_labels = np.array(HO_abbrev_labels,dtype = 'string')
            
            np_HO_labels = np.array(HO_labels,dtype = 'string')
            
            
            print template_indexes-1
            
            label_rois = np_HO_abbrev_labels[template_indexes-1]
            full_label_rois = np_HO_labels[template_indexes-1]
            
            #print label_rois2
            
            print label_rois
                        
                        
            #### indexed_mask
            indexed_mask_rois_file =  os.path.join(nipype_analyses_path,peak_activation_mask_analysis_name, "indexed_mask-" + ROI_mask_prefix + "_spm_contrast" + str(i+1) + ".nii")
                
            #### saving ROI coords as textfile
            ### ijk coords
            coord_rois_file =  os.path.join(nipype_analyses_path,peak_activation_mask_analysis_name, "coords-" + ROI_mask_prefix + "_spm_contrast" + str(i+1) + ".txt")

            ### coords in MNI space
            MNI_coord_rois_file =  os.path.join(nipype_analyses_path,peak_activation_mask_analysis_name, "coords-MNI-" + ROI_mask_prefix + "_spm_contrast" + str(i+1) + ".txt")

            #### saving ROI coords as textfile
            label_rois_file =  os.path.join(nipype_analyses_path,peak_activation_mask_analysis_name, "labels-" + ROI_mask_prefix + "_spm_contrast" + str(i+1) + ".txt")
            #label_rois_file =  os.path.join(nipype_analyses_path,peak_activation_mask_analysis_name, "labels-" + ROI_mask_prefix + "_jane.txt")
                
            #### all info in a text file
            info_rois_file  =  os.path.join(nipype_analyses_path,peak_activation_mask_analysis_name, "info-" + ROI_mask_prefix + "_spm_contrast" + str(i+1) + ".txt")


            
            
            
            
            #### exporting Rois image with different indexes 
            print np.unique(indexed_mask_rois_data)[1:].shape
            nib.save(nib.Nifti1Image(data = indexed_mask_rois_data,header = img_header,affine = img_affine),indexed_mask_rois_file)
            
            #### saving ROI coords as textfile
            np.savetxt(coord_rois_file,np.array(list_selected_peaks_coords,dtype = int), fmt = '%d')
            
            #### saving MNI coords as textfile
            list_rois_MNI_coords = [list_orig_peak_MNI_coords[index] for index in list_selected_peaks_indexes]
            
            print list_rois_MNI_coords
            
            rois_MNI_coords = np.array(list_rois_MNI_coords,dtype = int)
            np.savetxt(MNI_coord_rois_file,rois_MNI_coords, fmt = '%d')
            
            ### orig index of peaks
            list_rois_orig_indexes = [list_orig_ROI_spm_index[index] for index in list_selected_peaks_indexes]
            
            print list_rois_orig_indexes
            
            rois_orig_indexes = np.array(list_rois_orig_indexes,dtype = int).reshape(len(list_rois_orig_indexes),1)
            
            print rois_orig_indexes.shape
            
            #### saving labels 
            np.savetxt(label_rois_file,label_rois, fmt = '%s')
            
            ### saving all together for infosource
            np_label_rois = np.array(label_rois,dtype = 'string').reshape(len(label_rois),1)
            np_full_label_rois = np.array(full_label_rois,dtype = 'string').reshape(len(full_label_rois),1)
            
            print np_label_rois.shape
            print rois_MNI_coords.shape
            
            #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),np_full_label_rois,np_label_rois,rois_MNI_coords))
            #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),rois_MNI_coords))
            info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),np_full_label_rois,np_label_rois,rois_MNI_coords,rois_orig_indexes))
            
            print info_rois
        
            np.savetxt(info_rois_file,info_rois, fmt = '%s %s %s %s %s %s %s')
            
            indexed_mask_rois_files.append(indexed_mask_rois_file)
            coord_rois_files.append(coord_rois_file)
            
    return indexed_mask_rois_files,coord_rois_files
コード例 #5
0
def compute_labelled_mask_from_HO_and_merged_thr_spm_mask():

    write_dir = os.path.join(nipype_analyses_path,
                             peak_activation_mask_analysis_name)

    print(spm_contrasts_path)

    if not os.path.exists(write_dir):
        os.makedirs(write_dir)

    spm_contrast_indexes = [3, 4, 5, 8, 9, 10]

    spm_mask_files = [
        os.path.join(
            spm_contrasts_path, "_contrast_index_" + str(index) +
            "_group_contrast_index_0/spmT_0001_thr.img")
        for index in spm_contrast_indexes
    ]

    #spm_mask_files.sort()

    print(len(spm_mask_files))

    # prepare the data
    img = nib.load(spm_mask_files[0])

    img_header = img.get_header()
    img_affine = img.get_affine()
    img_shape = img.shape

    img_data = img.get_data()

    ########################## Computing combined HO areas

    resliced_full_HO_data, HO_labels, HO_abbrev_labels = compute_recombined_HO_template(
        img_header, img_affine, img_shape)

    ########################## Creating peak activation mask contrained by HO areas

    #print len(HO_abbrev_labels)
    #print len(HO_labels)

    #0/0
    np_HO_abbrev_labels = np.array(HO_abbrev_labels, dtype='string')

    np_HO_labels = np.array(HO_labels, dtype='string')

    template_indexes = np.unique(resliced_full_HO_data)[1:]

    #print template_indexes

    print(np_HO_labels.shape, np_HO_abbrev_labels.shape,
          template_indexes.shape)

    #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),np_full_label_rois,np_label_rois,rois_MNI_coords))
    #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),rois_MNI_coords))
    info_template = np.hstack(
        (template_indexes.reshape(len(HO_labels),
                                  1), np_HO_labels.reshape(len(HO_labels), 1),
         np_HO_abbrev_labels.reshape(len(HO_labels), 1)))
    #,rois_MNI_coords))

    print(info_template)

    np.savetxt(info_template_file, info_template, fmt='%s %s %s')

    #np.savetxt(info_template_file,info_rois, fmt = '%s %s %s %s %s %s')

    merged_mask_data = np.zeros(shape=img_shape, dtype=float)

    print(merged_mask_data.shape)

    list_orig_ROI_spm_index = []

    ### list for all info about peaks after merging between different contrasts
    list_orig_peak_coords = []
    list_orig_peak_MNI_coords = []
    list_orig_peak_vals = []

    for i, spm_mask_file in enumerate(spm_mask_files):

        print(spm_mask_file)

        spm_mask_img = nib.load(spm_mask_file)

        spm_mask_data = spm_mask_img.get_data()

        #### get peaks (avec la fonction stat_map.get_3d_peaks)
        peaks = stat_map.get_3d_peaks(image=spm_mask_img, mask=None)

        #print len(peaks)

        if peaks != None:

            print(len(peaks))
            list_orig_peak_vals = list_orig_peak_vals + [
                peak['val'] for peak in peaks
            ]
            list_orig_peak_coords = list_orig_peak_coords + [
                peak['ijk'] for peak in peaks
            ]
            list_orig_peak_MNI_coords = list_orig_peak_MNI_coords + [
                peak['pos'] for peak in peaks
            ]

            #print list_orig_peak_vals

            #print np.where(np.isnan(spm_mask_data))

            #print spm_mask_data[]

            #merged_mask_data[np.logical_and(spm_mask_data != 0.0, np.logical_not(np.isnan(spm_mask_data)))] = 1.0

            merged_mask_data[np.logical_and(
                spm_mask_data != 0.0,
                np.logical_not(np.isnan(spm_mask_data)))] += i + 1

            #print np.sum(np.logical_and(merged_mask_data != 0.0, np.logical_not(np.isnan(merged_mask_data))))

            list_orig_ROI_spm_index = list_orig_ROI_spm_index + [i + 1
                                                                 ] * len(peaks)

        print(len(list_orig_peak_coords))
        print(len(list_orig_ROI_spm_index))

    #### selectionne les pics sur leur distance entre eux et sur leur appatenance au template HO

    list_selected_peaks_coords, indexed_mask_rois_data, list_selected_peaks_indexes = remove_close_peaks_neigh_in_binary_template(
        list_orig_peak_coords, resliced_full_HO_data, min_dist_between_ROIs)
    #list_selected_peaks_coords,indexed_mask_rois_data,list_selected_peaks_indexes = remove_close_peaks_neigh_in_binary_template(sorded_merged_peaks_coords,resliced_full_HO_data,min_dist_between_ROIs)

    nib.save(
        nib.Nifti1Image(data=merged_mask_data,
                        header=img_header,
                        affine=img_affine), merged_mask_img_file)

    print(list_selected_peaks_indexes)
    print(len(list_selected_peaks_indexes))

    #for coord in list_selected_peaks_coords:

    #print coord
    ##template_indexes =
    #print resliced_full_HO_data[coord[0],coord[1],coord[2]]

    template_indexes = np.array([
        resliced_full_HO_data[coord[0], coord[1], coord[2]]
        for coord in list_selected_peaks_coords
    ],
                                dtype='int64')
    print(template_indexes)

    np_HO_abbrev_labels = np.array(HO_abbrev_labels, dtype='string')

    np_HO_labels = np.array(HO_labels, dtype='string')

    print(template_indexes - 1)

    label_rois = np_HO_abbrev_labels[template_indexes - 1]
    full_label_rois = np_HO_labels[template_indexes - 1]

    #print label_rois2

    print(label_rois)

    #### exporting Rois image with different indexes
    print(np.unique(indexed_mask_rois_data)[1:].shape)
    nib.save(
        nib.Nifti1Image(data=indexed_mask_rois_data,
                        header=img_header,
                        affine=img_affine), indexed_mask_rois_file)

    #### saving ROI coords as textfile
    np.savetxt(coord_rois_file,
               np.array(list_selected_peaks_coords, dtype=int),
               fmt='%d')

    #### saving MNI coords as textfile
    list_rois_MNI_coords = [
        list_orig_peak_MNI_coords[index]
        for index in list_selected_peaks_indexes
    ]

    print(list_rois_MNI_coords)

    rois_MNI_coords = np.array(list_rois_MNI_coords, dtype=int)
    np.savetxt(MNI_coord_rois_file, rois_MNI_coords, fmt='%d')

    ### orig index of peaks
    list_rois_orig_indexes = [
        list_orig_ROI_spm_index[index] for index in list_selected_peaks_indexes
    ]

    print(list_rois_orig_indexes)

    rois_orig_indexes = np.array(list_rois_orig_indexes, dtype=int).reshape(
        len(list_rois_orig_indexes), 1)

    print(rois_orig_indexes.shape)

    np.savetxt(rois_orig_indexes_file, rois_orig_indexes, fmt='%d')

    #### mask with orig spm index
    orig_spm_index_mask_data = np.zeros(shape=img_shape, dtype=int)

    print(np.unique(indexed_mask_rois_data))

    for i in np.unique(indexed_mask_rois_data)[1:]:

        print(i, np.sum(indexed_mask_rois_data == i), rois_orig_indexes[i])

        orig_spm_index_mask_data[indexed_mask_rois_data ==
                                 i] = rois_orig_indexes[i]

    nib.save(
        nib.Nifti1Image(data=orig_spm_index_mask_data,
                        header=img_header,
                        affine=img_affine), orig_spm_index_mask_file)

    #### saving labels
    np.savetxt(label_rois_file, label_rois, fmt='%s')

    ### saving all together for infosource
    np_label_rois = np.array(label_rois,
                             dtype='string').reshape(len(label_rois), 1)
    np_full_label_rois = np.array(full_label_rois, dtype='string').reshape(
        len(full_label_rois), 1)

    print(np_label_rois.shape)
    print(rois_MNI_coords.shape)

    #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),np_full_label_rois,np_label_rois,rois_MNI_coords))
    #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),rois_MNI_coords))
    info_rois = np.hstack(
        (np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),
                                                       1), np_full_label_rois,
         np_label_rois, rois_MNI_coords, rois_orig_indexes))

    print(info_rois)

    np.savetxt(info_rois_file, info_rois, fmt='%s %s %s %s %s %s %s')

    return indexed_mask_rois_file, coord_rois_file
コード例 #6
0
def compute_labelled_mask_from_HO_all_signif_contrasts():

    write_dir = os.path.join(nipype_analyses_path,
                             peak_activation_mask_analysis_name)

    print(spm_contrasts_path)

    if not os.path.exists(write_dir):
        os.makedirs(write_dir)

    #spm_mask_files =  glob.glob(os.path.join(spm_contrasts_path,rel_spm_mask_path,"_contrast_index_[1-6]_group_contrast_index_0/spmT_*.img"))
    spm_mask_files = glob.glob(
        os.path.join(spm_contrasts_path, contrast_pattern))

    print(spm_mask_files)

    print(spm_mask_files.sort())

    # prepare the data
    img = nib.load(spm_mask_files[0])

    img_header = img.get_header()
    img_affine = img.get_affine()
    img_shape = img.shape

    img_data = img.get_data()

    ########################## Computing combined HO areas

    resliced_full_HO_data, HO_labels, HO_abbrev_labels = compute_recombined_HO_template(
        img_header, img_affine, img_shape)

    ########################## Creating peak activation mask contrained by HO areas

    #print len(HO_abbrev_labels)
    #print len(HO_labels)

    #0/0
    np_HO_abbrev_labels = np.array(HO_abbrev_labels, dtype='string')

    np_HO_labels = np.array(HO_labels, dtype='string')

    template_indexes = np.unique(resliced_full_HO_data)[1:]

    #print template_indexes

    print(np_HO_labels.shape, np_HO_abbrev_labels.shape,
          template_indexes.shape)

    #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),np_full_label_rois,np_label_rois,rois_MNI_coords))
    #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),rois_MNI_coords))
    info_template = np.hstack(
        (template_indexes.reshape(len(HO_labels),
                                  1), np_HO_labels.reshape(len(HO_labels), 1),
         np_HO_abbrev_labels.reshape(len(HO_labels), 1)))
    #,rois_MNI_coords))

    print(info_template)

    np.savetxt(info_template_file, info_template, fmt='%s %s %s')

    #np.savetxt(info_template_file,info_rois, fmt = '%s %s %s %s %s %s')

    indexed_mask_rois_files = []

    coord_rois_files = []

    for i, spm_mask_file in enumerate(spm_mask_files):

        print(spm_mask_file)

        spm_mask_img = nib.load(spm_mask_file)

        spm_mask_data = spm_mask_img.get_data()

        #### get peaks (avec la fonction stat_map.get_3d_peaks)
        peaks = stat_map.get_3d_peaks(image=spm_mask_img,
                                      mask=None,
                                      threshold=threshold,
                                      nn=cluster_nbvoxels)

        #print len(peaks)

        list_orig_ROI_spm_index = []

        if peaks != None:

            print(len(peaks))
            list_orig_peak_vals = [peak['val'] for peak in peaks]
            list_orig_peak_coords = [peak['ijk'] for peak in peaks]
            list_orig_peak_MNI_coords = [peak['pos'] for peak in peaks]

            merged_mask_data = spm_mask_data[np.logical_and(
                spm_mask_data != 0.0, np.logical_not(np.isnan(spm_mask_data)))]

            list_orig_ROI_spm_index = list_orig_ROI_spm_index + [i + 1
                                                                 ] * len(peaks)

            print(len(list_orig_peak_coords))
            print(len(list_orig_ROI_spm_index))

            list_selected_peaks_coords, indexed_mask_rois_data, list_selected_peaks_indexes = remove_close_peaks_neigh_in_binary_template(
                list_orig_peak_coords, resliced_full_HO_data,
                min_dist_between_ROIs)

            print(list_selected_peaks_indexes)
            print(len(list_selected_peaks_indexes))

            merged_mask_data[indexed_mask_rois_data != 0] += i + 1

            template_indexes = np.array([
                resliced_full_HO_data[coord[0], coord[1], coord[2]]
                for coord in list_selected_peaks_coords
            ],
                                        dtype='int64')
            print(template_indexes)

            np_HO_abbrev_labels = np.array(HO_abbrev_labels, dtype='string')

            np_HO_labels = np.array(HO_labels, dtype='string')

            print(template_indexes - 1)

            label_rois = np_HO_abbrev_labels[template_indexes - 1]
            full_label_rois = np_HO_labels[template_indexes - 1]

            #print label_rois2

            print(label_rois)

            #### indexed_mask
            indexed_mask_rois_file = os.path.join(
                nipype_analyses_path, peak_activation_mask_analysis_name,
                "indexed_mask-" + ROI_mask_prefix + "_spm_contrast" +
                str(i + 1) + ".nii")

            #### saving ROI coords as textfile
            ### ijk coords
            coord_rois_file = os.path.join(
                nipype_analyses_path, peak_activation_mask_analysis_name,
                "coords-" + ROI_mask_prefix + "_spm_contrast" + str(i + 1) +
                ".txt")

            ### coords in MNI space
            MNI_coord_rois_file = os.path.join(
                nipype_analyses_path, peak_activation_mask_analysis_name,
                "coords-MNI-" + ROI_mask_prefix + "_spm_contrast" +
                str(i + 1) + ".txt")

            #### saving ROI coords as textfile
            label_rois_file = os.path.join(
                nipype_analyses_path, peak_activation_mask_analysis_name,
                "labels-" + ROI_mask_prefix + "_spm_contrast" + str(i + 1) +
                ".txt")
            #label_rois_file =  os.path.join(nipype_analyses_path,peak_activation_mask_analysis_name, "labels-" + ROI_mask_prefix + "_jane.txt")

            #### all info in a text file
            info_rois_file = os.path.join(
                nipype_analyses_path, peak_activation_mask_analysis_name,
                "info-" + ROI_mask_prefix + "_spm_contrast" + str(i + 1) +
                ".txt")

            #### exporting Rois image with different indexes
            print(np.unique(indexed_mask_rois_data)[1:].shape)
            nib.save(
                nib.Nifti1Image(data=indexed_mask_rois_data,
                                header=img_header,
                                affine=img_affine), indexed_mask_rois_file)

            #### saving ROI coords as textfile
            np.savetxt(coord_rois_file,
                       np.array(list_selected_peaks_coords, dtype=int),
                       fmt='%d')

            #### saving MNI coords as textfile
            list_rois_MNI_coords = [
                list_orig_peak_MNI_coords[index]
                for index in list_selected_peaks_indexes
            ]

            print(list_rois_MNI_coords)

            rois_MNI_coords = np.array(list_rois_MNI_coords, dtype=int)
            np.savetxt(MNI_coord_rois_file, rois_MNI_coords, fmt='%d')

            ### orig index of peaks
            list_rois_orig_indexes = [
                list_orig_ROI_spm_index[index]
                for index in list_selected_peaks_indexes
            ]

            print(list_rois_orig_indexes)

            rois_orig_indexes = np.array(list_rois_orig_indexes,
                                         dtype=int).reshape(
                                             len(list_rois_orig_indexes), 1)

            print(rois_orig_indexes.shape)

            #### saving labels
            np.savetxt(label_rois_file, label_rois, fmt='%s')

            ### saving all together for infosource
            np_label_rois = np.array(label_rois, dtype='string').reshape(
                len(label_rois), 1)
            np_full_label_rois = np.array(full_label_rois,
                                          dtype='string').reshape(
                                              len(full_label_rois), 1)

            print(np_label_rois.shape)
            print(rois_MNI_coords.shape)

            #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),np_full_label_rois,np_label_rois,rois_MNI_coords))
            #info_rois = np.hstack((np.unique(indexed_mask_rois_data)[1:].reshape(len(label_rois),1),rois_MNI_coords))
            info_rois = np.hstack(
                (np.unique(indexed_mask_rois_data)[1:].reshape(
                    len(label_rois), 1), np_full_label_rois, np_label_rois,
                 rois_MNI_coords, rois_orig_indexes))

            print(info_rois)

            np.savetxt(info_rois_file, info_rois, fmt='%s %s %s %s %s %s %s')

            indexed_mask_rois_files.append(indexed_mask_rois_file)
            coord_rois_files.append(coord_rois_file)

    return indexed_mask_rois_files, coord_rois_files