예제 #1
0
파일: freeview.py 프로젝트: pelednoam/mmvt
def create_lut_file_for_atlas(subject, atlas):
    # Read the subcortical segmentation from the freesurfer lut
    lut = utils.read_freesurfer_lookup_table(FREE_SURFER_HOME, get_colors=True)
    lut_new = [list(l) for l in lut if l[0] < 1000]
    for hemi, offset in zip(['lh', 'rh'], [1000, 2000]):
        if hemi == 'lh':
            lut_new.append([1000, 'ctx-lh-unknown', 25, 5,  25, 0])
        else:
            lut_new.append([2000, 'ctx-rh-unknown', 25,  5, 25,  0])
        _, ctab, names = _read_annot(op.join(SUBJECTS_DIR, subject, 'label', '{}.{}.annot'.format(hemi, atlas)))
        names = [name.astype(str) for name in names]
        for index, (label, cval) in enumerate(zip(names, ctab)):
            r,g,b,a, _ = cval
            lut_new.append([index + offset + 1, label, r, g, b, a])
    lut_new.sort(key=lambda x:x[0])
    # Add the values above 3000
    for l in [l for l in lut if l[0] >= 3000]:
        lut_new.append(l)
    new_lut_fname = op.join(SUBJECTS_DIR, subject, 'label', '{}ColorLUT.txt'.format(atlas))
    with open(new_lut_fname, 'w') as fp:
        csv_writer = csv.writer(fp, delimiter='\t')
        csv_writer.writerows(lut_new)
    # np.savetxt(new_lut_fname, lut_new, delimiter='\t', fmt="%s")
    utils.make_dir(op.join(MMVT_DIR, subject, 'freeview'))
    shutil.copyfile(new_lut_fname, op.join(MMVT_DIR, subject, 'freeview', '{}ColorLUT.txt'.format(atlas)))
예제 #2
0
파일: anatomy.py 프로젝트: pelednoam/mmvt
def split_cerebellum_hemis(subject, mask_fname, new_maks_name, subregions_num):
    import time
    if op.isfile(new_maks_name):
        return subregions_num * 2
    mask = nib.load(mask_fname)
    mask_data = mask.get_data()
    aseg_data = nib.load(op.join(SUBJECTS_DIR, subject, 'mri', 'aseg.mgz')).get_data()
    new_mask_data = np.zeros(mask_data.shape)
    lookup = utils.read_freesurfer_lookup_table(return_dict=True)
    inv_lookup = {name:val for val,name in lookup.items()}
    right_cerebral = inv_lookup['Right-Cerebellum-Cortex']
    left_cerebral = inv_lookup['Left-Cerebellum-Cortex']
    now = time.time()
    for seg_id in range(1, subregions_num + 1):
        utils.time_to_go(now, seg_id-1, subregions_num, 1)
        seg_inds = np.where(mask_data == seg_id)
        aseg_segs = aseg_data[seg_inds]
        seg_inds = np.vstack((seg_inds[0], seg_inds[1], seg_inds[2]))
        right_inds = seg_inds[:, np.where(aseg_segs == right_cerebral)[0]]
        left_inds = seg_inds[:, np.where(aseg_segs == left_cerebral)[0]]
        new_mask_data[right_inds[0], right_inds[1], right_inds[2]] = seg_id
        new_mask_data[left_inds[0], left_inds[1], left_inds[2]] = seg_id + subregions_num
    new_mask = nib.Nifti1Image(new_mask_data, affine=mask.get_affine())
    print('Saving new mask to {}'.format(new_maks_name))
    nib.save(new_mask, new_maks_name)
    return subregions_num * 2
예제 #3
0
def create_lut_file_for_atlas(subject, atlas):
    # Read the subcortical segmentation from the freesurfer lut
    lut = utils.read_freesurfer_lookup_table(FREE_SURFER_HOME, get_colors=True)
    lut_new = [list(l) for l in lut if l[0] < 1000]
    for hemi, offset in zip(['lh', 'rh'], [1000, 2000]):
        if hemi == 'lh':
            lut_new.append([1000, 'ctx-lh-unknown', 25, 5, 25, 0])
        else:
            lut_new.append([2000, 'ctx-rh-unknown', 25, 5, 25, 0])
        _, ctab, names = _read_annot(
            op.join(SUBJECTS_DIR, subject, 'label',
                    '{}.{}.annot'.format(hemi, atlas)))
        names = [name.astype(str) for name in names]
        for index, (label, cval) in enumerate(zip(names, ctab)):
            r, g, b, a, _ = cval
            lut_new.append([index + offset + 1, label, r, g, b, a])
    lut_new.sort(key=lambda x: x[0])
    # Add the values above 3000
    for l in [l for l in lut if l[0] >= 3000]:
        lut_new.append(l)
    new_lut_fname = op.join(SUBJECTS_DIR, subject, 'label',
                            '{}ColorLUT.txt'.format(atlas))
    with open(new_lut_fname, 'w') as fp:
        csv_writer = csv.writer(fp, delimiter='\t')
        csv_writer.writerows(lut_new)
    # np.savetxt(new_lut_fname, lut_new, delimiter='\t', fmt="%s")
    utils.make_dir(op.join(BLENDER_ROOT_DIR, subject, 'freeview'))
    shutil.copyfile(
        new_lut_fname,
        op.join(BLENDER_ROOT_DIR, subject, 'freeview',
                '{}ColorLUT.txt'.format(atlas)))
예제 #4
0
def create_lut_file_for_atlas(subject, atlas):
    if not utils.both_hemi_files_exist(
            op.join(SUBJECTS_DIR, subject, 'label', '{}.{}.annot'.format(
                '{hemi}', atlas))):
        print('No annot file was found for {}!'.format(atlas))
        print(
            'Run python -m src.preproc.anatomy -s {} -a {} -f create_surfaces,create_annotation'
            .format(subject, atlas))
        return False

    # Read the subcortical segmentation from the freesurfer lut
    new_lut_fname = op.join(SUBJECTS_DIR, subject, 'label',
                            '{}ColorLUT.txt'.format(atlas))
    mmvt_lut_fname = op.join(MMVT_DIR, subject, 'freeview',
                             '{}ColorLUT.txt'.format(atlas))
    # if op.isfile(mmvt_lut_fname) and not args.overwrite_aseg_file:
    #     return
    lut = utils.read_freesurfer_lookup_table(get_colors=True)
    lut_new = [[l[0], l[1].astype(str), l[2], l[3], l[4], l[5]] for l in lut
               if l[0] < 1000]
    for hemi, offset in zip(['lh', 'rh'], [1000, 2000]):
        if hemi == 'lh':
            lut_new.append([offset, 'ctx-lh-unknown', 25, 5, 25, 0])
        else:
            lut_new.append([offset, 'ctx-rh-unknown', 25, 5, 25, 0])
        _, ctab, names = _read_annot(
            op.join(SUBJECTS_DIR, subject, 'label',
                    '{}.{}.annot'.format(hemi, atlas)))
        names = [name.astype(str) for name in names]
        for index, (label, cval) in enumerate(zip(names, ctab)):
            r, g, b, a, _ = cval
            lut_new.append([index + offset + 1, label, r, g, b, a])
    lut_new.sort(key=lambda x: x[0])
    # Add the values above 3000
    for l in [l for l in lut if l[0] >= 3000]:
        lut_new.append([l[0], l[1].astype(str), l[2], l[3], l[4], l[5]])
    with open(new_lut_fname, 'w') as fp:
        csv_writer = csv.writer(fp, delimiter='\t')
        csv_writer.writerows(lut_new)
    # np.savetxt(new_lut_fname, lut_new, delimiter='\t', fmt="%s")
    utils.make_dir(op.join(MMVT_DIR, subject, 'freeview'))
    shutil.copyfile(new_lut_fname, mmvt_lut_fname)
    lut_npz_fname = utils.change_fname_extension(mmvt_lut_fname, 'npz')
    x = np.genfromtxt(mmvt_lut_fname, dtype=np.str)
    np.savez(lut_npz_fname, names=x[:, 1], ids=x[:, 0].astype(int))
    return op.isfile(mmvt_lut_fname) and op.isfile(lut_npz_fname)
예제 #5
0
파일: cics.py 프로젝트: bdthombre/mmvt
def calc_cbf_histograms(subject,
                        scan_rescan,
                        low_threshold,
                        high_threshold,
                        cortex_frac_threshold=0.9,
                        overwrite=False,
                        do_plot=True):
    subject_fol = op.join(HOME_FOL, site, subject, scan_rescan)
    output_fol = utils.make_dir(
        op.join(op.join(RESULTS_FOL, 'aparc_aseg_hists', subject,
                        scan_rescan)))
    values_output_fname = op.join(
        op.join(RESULTS_FOL, 'aparc_aseg_hists', subject, scan_rescan,
                'aparc_aseg_hist.pkl'))
    means_output_fname = op.join(
        op.join(RESULTS_FOL, 'aparc_aseg_hists', subject, scan_rescan,
                'aparc_values.pkl'))
    if op.isfile(values_output_fname) and op.isfile(
            means_output_fname) and not overwrite and not do_plot:
        return True
    cics_cbf_fname = op.join(HOME_FOL, site, subject, scan_rescan, 'CBF.nii')
    if not op.isfile(cics_cbf_fname):
        print('calc_cbf_histograms: Cannot find {}!'.format(cics_cbf_fname))
        return False
    aparc_aseg_fname = op.join(subject_fol, 'aparc+aseg_cbf.mgz')
    if not op.isfile(aparc_aseg_fname):
        print('calc_cbf_histograms: Cannot find {}!'.format(aparc_aseg_fname))
        return False
    cortex_frac_fname = op.join(HOME_FOL, site, subject, scan_rescan,
                                'CBF.cortex.mgz')
    if not op.isfile(cortex_frac_fname):
        print('No cortex frac!')
        return False
    cbf_data = nib.load(cics_cbf_fname).get_data()
    cortex_frac = nib.load(cortex_frac_fname).get_data()
    lut = utils.read_freesurfer_lookup_table(return_dict=True)
    aparc_aseg = nib.load(aparc_aseg_fname).get_data()
    unique_codes = list(range(1001, 1036)) + list(range(2001, 2036))
    if overwrite and do_plot:
        utils.delete_folder_files(output_fol)
    regions_values, regions_means = {}, {}
    output_str = ''
    for code in tqdm(unique_codes):
        region_name = lut.get(code, None)
        if region_name is None:
            # print('{} not in lut!'.format(code))
            continue
        fig_fname = op.join(output_fol, '{}.jpg'.format(region_name))
        if op.isfile(fig_fname) and not overwrite:
            continue
        region_values = cbf_data[np.where(aparc_aseg == code)]
        cortex_frac_values = cortex_frac[np.where(aparc_aseg == code)]
        cortex_indices = np.where(cortex_frac_values > cortex_frac_threshold)
        if len(cortex_indices[0]) == 0:
            output_str += '{} has no voxels with cortex_frac > {}!\n'.format(
                region_name, cortex_frac_threshold)
            continue
        region_values = region_values[cortex_indices]
        # regions_values[region_name] = region_values.copy()
        in_bounderies_indices = np.where((low_threshold < region_values)
                                         & (region_values < high_threshold))
        region_values = region_values[in_bounderies_indices]
        regions_values[region_name] = region_values.copy()
        regions_means[region_name] = np.mean(regions_values[region_name])
        # if len(outliers) > 0:
        #     output_str += '{} has {} out of {} values < {}\n'.format(
        #         region_name, len(outliers), len(region_values), low_threshold)
        # outliers = np.where(region_values > high_threshold)[0]
        # if len(outliers) > 0:
        #     output_str += '{} has {} out of {} values > {}\n'.format(
        #         region_name, len(outliers), len(region_values), high_threshold)
        # region_values[region_values < low_threshold] = low_threshold
        # region_values[region_values > high_threshold] = high_threshold
        if do_plot:
            plt.hist(region_values, bins=40)
            plt.savefig(fig_fname)
            plt.close()
    print(output_str)
    utils.save(regions_values, values_output_fname)
    utils.save(regions_means, means_output_fname)