Exemple #1
0
def init(addon):
    AppearanceMakerPanel.addon = addon
    register()
    AppearanceMakerPanel.init = True
    bpy.context.scene.subcortical_layer = 'fmri'
    change_to_solid_brain()
    # show_rois()
    loc_val = 0  #5
    AppearanceMakerPanel.flat_map_exists = True
    bpy.context.scene.show_appearance_settings = False
    if bpy.data.objects.get('Cortex-inflated-rh') and bpy.data.objects.get(
            'inflated_rh'):
        AppearanceMakerPanel.cortex_inflated_rh = bpy.data.objects['Cortex-inflated-rh'].location[0] = \
            bpy.data.objects['inflated_rh'].location[0] = loc_val
        AppearanceMakerPanel.cortex_inflated_lh = bpy.data.objects['Cortex-inflated-lh'].location[0] = \
            bpy.data.objects['inflated_lh'].location[0] = -1*loc_val
        try:
            bpy.data.shape_keys['Key'].key_blocks["flat"].value = 0
            bpy.data.shape_keys['Key.001'].key_blocks["flat"].value = 0
        except:
            print('No flat mapping.')
            AppearanceMakerPanel.flat_map_exists = False
        try:
            bpy.data.shape_keys['Key'].key_blocks["inflated"].value = 1
            bpy.data.shape_keys['Key.001'].key_blocks["inflated"].value = 1
        except:
            AppearanceMakerPanel.flat_map_exists = False
            print('No inflated mapping.')

        for hemi in ['lh', 'rh']:
            try:
                mu.get_hemi_obj(
                    hemi).modifiers['mask_bad_vertices'].show_viewport = True
                mu.get_hemi_obj(
                    hemi).modifiers['mask_bad_vertices'].show_render = True
            except:
                pass
    if bpy.data.objects.get('Cortex-rh') and bpy.data.objects.get('lh'):
        AppearanceMakerPanel.cortex_rh = bpy.data.objects['Cortex-rh'].location[0] = \
            bpy.data.objects['rh'].location[0] = 0
        AppearanceMakerPanel.cortex_lh = bpy.data.objects['Cortex-lh'].location[0] = \
            bpy.data.objects['rh'].location[0] = 0
    bpy.context.scene.hemis_distance = 0
    bpy.context.scene.hemis_inf_distance = 0  #-5
    bpy.context.scene.cursor_is_snapped = True
    # set_inflated_ratio(0)
    appearance_show_rois_activity_update()
    AppearanceMakerPanel.showing_meg_sensors = showing_meg_sensors()
    AppearanceMakerPanel.showing_eeg_sensors = showing_eeg()
    AppearanceMakerPanel.showing_electrodes = showing_electordes()
    # AppearanceMakerPanel.mesh = {hemi:mu.get_hemi_obj(hemi).to_mesh(bpy.context.scene, True, 'PREVIEW')
    #                              for hemi in mu.HEMIS}
    # show_inflated()
    bpy.context.scene.panels_background_color = [0, 0, 0]
    snap_cursor(True)
    AppearanceMakerPanel.init = True
def _save_image():
    if not bpy.context.scene.save_split_views:
        save_image(view_selected=bpy.context.scene.save_selected_view,
                   add_colorbar=bpy.context.scene.save_views_with_cb)
    else:
        images = {}
        org_hide = {hemi: mu.get_hemi_obj(hemi).hide for hemi in mu.HEMIS}
        for hemi in mu.HEMIS:
            mu.get_hemi_obj(hemi).hide = False
            mu.get_hemi_obj(mu.other_hemi(hemi)).hide = True
            images[hemi] = save_image(view_selected=bpy.context.scene.save_selected_view, add_colorbar=False)
        for hemi in mu.HEMIS:
            mu.get_hemi_obj(hemi).hide = org_hide[hemi]
        combine_two_images_and_add_colorbar(images['lh'], images['rh'], images['lh'])
def save_all_views(views=None, inflated_ratio_in_file_name=False, rot_lh_axial=None, render_images=False, quality=0,
                   img_name_prefix='', add_colorbar=None, cb_ticks_num=None, cb_ticks_font_size=None, overwrite=True):
    if not render_images:
        _addon().change_to_solid_brain()
    if add_colorbar is None:
        add_colorbar = bpy.context.scene.save_views_with_cb
    if cb_ticks_num is None:
        cb_ticks_num = bpy.context.scene.cb_ticks_num
    if cb_ticks_font_size is None:
        cb_ticks_font_size = bpy.context.scene.cb_ticks_font_size

    _addon().show_hemis()
    if not bpy.context.scene.save_split_views:
        rot_lh_axial = False if rot_lh_axial is None else rot_lh_axial
        _save_all_views(views, inflated_ratio_in_file_name, rot_lh_axial, render_images, quality,  img_name_prefix,
                        add_colorbar, cb_ticks_num, cb_ticks_font_size, overwrite)
    else:
        if views is None:
            views = list(set(_addon().ANGLES_DICT.keys()) - set([_addon().ROT_MEDIAL_LEFT, _addon().ROT_MEDIAL_RIGHT]))
        images_names = []
        rot_lh_axial = True if rot_lh_axial is None else rot_lh_axial
        org_hide = {hemi: mu.get_hemi_obj(hemi).hide for hemi in mu.HEMIS}
        for hemi in mu.HEMIS:
            mu.get_hemi_obj(hemi).hide = False
            mu.get_hemi_obj(mu.other_hemi(hemi)).hide = True
            images_names.extend(_save_all_views(
                views, inflated_ratio_in_file_name, rot_lh_axial, render_images, quality,  img_name_prefix, False,
                overwrite=overwrite))
        for hemi in mu.HEMIS:
            mu.get_hemi_obj(hemi).hide = org_hide[hemi]
        images_hemi_inv_list = set(
            [mu.namebase(fname)[3:] for fname in images_names if mu.namebase(fname)[:2] in ['rh', 'lh']])
        files = [[fname for fname in images_names if mu.namebase(fname)[3:] == img_hemi_inv] for img_hemi_inv in
                 images_hemi_inv_list]
        fol = mu.get_fname_folder(files[0][0])
        for files_coup in files:
            hemi = 'rh' if mu.namebase(files_coup[0]).startswith('rh') else 'lh'
            coup_template = files_coup[0].replace(hemi, '{hemi}')
            coup = {hemi: coup_template.format(hemi=hemi) for hemi in mu.HEMIS}
            new_image_fname = op.join(fol, mu.namebase_with_ext(files_coup[0])[3:])
            combine_two_images_and_add_colorbar(
                coup['lh'], coup['rh'], new_image_fname, cb_ticks_num, cb_ticks_font_size)
    _addon().show_hemis()
Exemple #4
0
def clear_contours():
    # todo: there is a better way to do it
    labels_contours = LabelsPanel.labels_contours
    for hemi in mu.HEMIS:
        contours = labels_contours[hemi]['contours']
        selected_contours = np.zeros(contours.shape)
        mesh = mu.get_hemi_obj(hemi).data
        mesh.vertex_colors.active_index = mesh.vertex_colors.keys().index('contours')
        mesh.vertex_colors['contours'].active_render = True
        _addon().color_hemi_data(hemi, selected_contours, 0.1, 256, override_current_mat=True,
                        coloring_layer='contours', check_valid_verts=False)
Exemple #5
0
def color_contours(specific_labels=[], specific_hemi='both', labels_contours=None, cumulate=False, change_colorbar=False,
                   specific_colors=None, atlas='', move_cursor=True):
    if _addon() is None:
        return
    if isinstance(specific_labels, str):
        specific_labels = [specific_labels]
    if atlas != '' and atlas != bpy.context.scene.contours_coloring and atlas in LabelsPanel.existing_contoures:
        bpy.context.scene.contours_coloring = atlas
    if atlas == '' and bpy.context.scene.atlas in LabelsPanel.existing_contoures:
        bpy.context.scene.contours_coloring = bpy.context.scene.atlas
    if labels_contours is None:
        labels_contours = LabelsPanel.labels_contours
    contour_max = max([labels_contours[hemi]['max'] for hemi in mu.HEMIS])
    if not _addon().colorbar_values_are_locked() and change_colorbar:
        _addon().set_colormap('jet')
        _addon().set_colorbar_title('{} labels contours'.format(bpy.context.scene.contours_coloring))
        _addon().set_colorbar_max_min(contour_max, 1)
        _addon().set_colorbar_prec(0)
    _addon().show_activity()
    specific_label_ind = 0
    if specific_colors is not None:
        specific_colors = np.tile(specific_colors, (len(specific_labels), 1))
    for hemi in mu.HEMIS:
        contours = labels_contours[hemi]['contours']
        if specific_hemi != 'both' and hemi != specific_hemi:
            selected_contours = np.zeros(contours.shape) if specific_colors is None else np.zeros((contours.shape[0], 4))
        elif len(specific_labels) > 0:
            selected_contours = np.zeros(contours.shape) if specific_colors is None else np.zeros((contours.shape[0], 4))
            for specific_label in specific_labels:
                if mu.get_hemi_from_fname(specific_label) != hemi:
                    continue
                label_ind = np.where(np.array(labels_contours[hemi]['labels']) == specific_label)
                if len(label_ind) > 0 and len(label_ind[0]) > 0:
                    label_ind = label_ind[0][0]
                    selected_contours[np.where(contours == label_ind + 1)] = \
                        label_ind + 1 if specific_colors is None else [1, *specific_colors[specific_label_ind]]
                    specific_label_ind += 1
                    if move_cursor and len(specific_labels) == 1 and 'centers' in labels_contours[hemi]:
                        vert = labels_contours[hemi]['centers'][label_ind]
                        _addon().move_cursor_according_to_vert(vert, 'inflated_{}'.format(hemi))
                        _addon().set_closest_vertex_and_mesh_to_cursor(vert, 'inflated_{}'.format(hemi))
                        _addon().create_slices()
                else:
                    print("Can't find {} in the labels contours!".format(specific_label))
        else:
            selected_contours = labels_contours[hemi]['contours']
        mesh = mu.get_hemi_obj(hemi).data
        mesh.vertex_colors.active_index = mesh.vertex_colors.keys().index('contours')
        mesh.vertex_colors['contours'].active_render = True
        _addon().color_hemi_data(hemi, selected_contours, 0.1, 256 / contour_max, override_current_mat=not cumulate,
                        coloring_layer='contours', check_valid_verts=False)
    _addon().what_is_colored().add(_addon().WIC_CONTOURS)
Exemple #6
0
def view_name(view):
    if mu.get_hemi_obj('rh').hide and not mu.get_hemi_obj('lh').hide:
        hemi = 'lh'
    elif not mu.get_hemi_obj('rh').hide and mu.get_hemi_obj('lh').hide:
        hemi = 'rh'
    elif not mu.get_hemi_obj('rh').hide and not mu.get_hemi_obj('lh').hide:
        hemi = 'both'
    if (hemi == 'rh' and view == ROT_SAGITTAL_LEFT) or (hemi == 'lh' and view == ROT_SAGITTAL_RIGHT):
        view_name = 'medial'
    elif (hemi == 'lh' and view == ROT_SAGITTAL_LEFT) or (hemi == 'rh' and view == ROT_SAGITTAL_RIGHT):
        view_name = 'lateral'
    else:
        view_name = ANGLES_NAMES_DICT[view]
    return view_name
Exemple #7
0
def _inflating_update():
    try:
        if bpy.data.objects.get('rh', None) is None:
            return
        if bpy.context.scene.inflating > 0:  #flattening
            # _addon().show_coronal(True)
            # _addon().view_all()
            if AppearanceMakerPanel.flat_map_exists:
                bpy.data.shape_keys['Key'].key_blocks[
                    "flat"].value = bpy.context.scene.inflating
                bpy.data.shape_keys['Key.001'].key_blocks[
                    "flat"].value = bpy.context.scene.inflating
            bpy.data.shape_keys['Key'].key_blocks["inflated"].value = 1
            bpy.data.shape_keys['Key.001'].key_blocks["inflated"].value = 1

            bpy.data.objects['inflated_rh'].location[
                0] = 10 * bpy.context.scene.inflating
            bpy.data.objects['inflated_lh'].location[
                0] = -10 * bpy.context.scene.inflating
            # bpy.data.objects['inflated_rh'].location[0] = bpy.context.scene.inflating
            # bpy.data.objects['inflated_lh'].location[0] = bpy.context.scene.inflating

            use_masking = True
        else:  #deflating
            bpy.data.shape_keys['Key'].key_blocks[
                "inflated"].value = bpy.context.scene.inflating + 1
            bpy.data.shape_keys['Key.001'].key_blocks[
                "inflated"].value = bpy.context.scene.inflating + 1
            if AppearanceMakerPanel.flat_map_exists:
                bpy.data.shape_keys['Key'].key_blocks["flat"].value = 0
                bpy.data.shape_keys['Key.001'].key_blocks["flat"].value = 0

            bpy.data.objects['inflated_rh'].location[0] = 0
            bpy.data.objects['inflated_lh'].location[0] = 0
            use_masking = False

        # mu.set_zoom_level(bpy.context.scene.surface_type, abs(bpy.context.scene.inflating))
        bpy.context.scene.layers[_addon().ACTIVITY_LAYER] = False
        bpy.context.scene.layers[_addon().ELECTRODES_LAYER] = False

        AppearanceMakerPanel.no_surface_type_update = True
        infl = bpy.context.scene.inflating
        if 0 < infl <= 1.0:
            bpy.context.scene.surface_type = 'flat'
            _addon().show_coronal(True)
        elif -1.0 < infl <= 0.0:
            bpy.context.scene.surface_type = 'inflated'
        elif infl == -1.0:
            bpy.context.scene.surface_type = 'pial'
            bpy.context.scene.layers[_addon().ACTIVITY_LAYER] = True
            if bpy.context.scene.show_hide_electrodes:
                bpy.context.scene.layers[_addon().ELECTRODES_LAYER] = True
        AppearanceMakerPanel.no_surface_type_update = False

        if AppearanceMakerPanel.flat_map_exists:
            for hemi in ['rh', 'lh']:
                mu.get_hemi_obj(hemi).modifiers[
                    'mask_bad_vertices'].show_viewport = use_masking
                mu.get_hemi_obj(hemi).modifiers[
                    'mask_bad_vertices'].show_render = use_masking
                # print(use_masking)
        # bpy.context.scene.hemis_inf_distance = - (1 - bpy.context.scene.inflating) * 5

        if bpy.context.scene.cursor_is_snapped:
            vert, obj_name = get_closest_vertex_and_mesh_to_cursor()
            if obj_name != '':
                if 'inflated' not in obj_name:
                    obj_name = 'inflated_{}'.format(obj_name)
                obj = bpy.data.objects[obj_name]
                move_cursor_according_to_vert(vert, obj)

    except:
        print('Error in inflating update!')
        print(traceback.format_exc())
def _save_all_views(views=None,
                    inflated_ratio_in_file_name=False,
                    rot_lh_axial=True,
                    render_images=False,
                    quality=0,
                    img_name_prefix='',
                    add_colorbar=False,
                    cb_ticks_num=None,
                    cb_ticks_font_size=None,
                    overwrite=True):
    def get_image_name(view_name):
        return '{}{}{}_{}'.format(
            '{}_'.format(hemi) if hemi != '' else '',
            '{}_'.format(img_name_prefix) if img_name_prefix != '' else '',
            surf_name, view_name)

    def should_save_image(img_name):
        return overwrite or not op.isfile(get_full_output_fname(img_name))

    def save_medial_views():
        if _addon().ROT_MEDIAL_LEFT in views:
            image_name = '{}_left_medial'.format(surf_name)
            if should_save_image(image_name):
                _addon().hide_hemi('rh')
                _addon().show_hemi('lh')
                _addon().rotate_view(_addon().ROT_SAGITTAL_RIGHT)
                image_fname = save_render_image(image_name, quality,
                                                render_images, add_colorbar,
                                                cb_ticks_num,
                                                cb_ticks_font_size)
                images_names.append(image_fname)
        if _addon().ROT_MEDIAL_RIGHT in views:
            image_name = '{}_right_medial'.format(surf_name)
            if should_save_image(image_name):
                _addon().show_hemi('rh')
                _addon().hide_hemi('lh')
                _addon().rotate_view(_addon().ROT_SAGITTAL_LEFT)
                image_fname = save_render_image(
                    '{}_right_medial'.format(surf_name), quality,
                    render_images, add_colorbar, cb_ticks_num,
                    cb_ticks_font_size)
                images_names.append(image_fname)
        _addon().show_hemi('rh')
        _addon().show_hemi('lh')

    if views is None:
        views = list(_addon().ANGLES_DICT.keys(
        ))  # + [_addon().ROT_MEDIAL_LEFT, _addon().ROT_MEDIAL_RIGHT]
    else:
        views = list(map(int, views))
    inf_r = bpy.context.scene.inflating
    if inflated_ratio_in_file_name:
        surf_name_dict = {-1: 'pial', 0: 'inflated', 1: 'flat'}
        surf_name = surf_name_dict.get(inf_r, '')
        if surf_name == '':
            if -1 < inf_r < 0:
                surf_name = '{:.1f}_inflated'.format(1 - inf_r)
            else:
                surf_name = '{:.1f}_flat'.format(inf_r)
    else:
        surf_name = 'pial' if inf_r == -1 else 'inflated' if -1 < inf_r <= 0 else 'flat'
    if mu.get_hemi_obj('rh').hide and not mu.get_hemi_obj('lh').hide:
        hemi = 'lh'
    elif not mu.get_hemi_obj('rh').hide and mu.get_hemi_obj('lh').hide:
        hemi = 'rh'
    elif not mu.get_hemi_obj('rh').hide and not mu.get_hemi_obj('lh').hide:
        hemi = ''
    else:
        mu.write_to_stderr('You need to show at least one hemi')
    org_view_ang = tuple(mu.get_view3d_region().view_rotation)
    images_names = []
    for view in views:
        view_name = _addon().view_name(view)
        img_name = get_image_name(view_name)
        if not should_save_image(img_name):
            continue
        _addon().rotate_view(view)
        if hemi == 'lh' and rot_lh_axial and view in (
                _addon().ROT_AXIAL_SUPERIOR, _addon().ROT_AXIAL_INFERIOR):
            _addon().rotate_brain(dz=180)
        mu.center_view()
        image_fname = save_render_image(img_name, quality, render_images,
                                        add_colorbar, cb_ticks_num,
                                        cb_ticks_font_size)
        print(image_fname, view, hemi)
        images_names.append(image_fname)
    # if not mu.get_hemi_obj('rh').hide and not mu.get_hemi_obj('lh').hide:
    if views is None:
        save_medial_views()
    # todo: doesn't work
    mu.rotate_view3d(org_view_ang)
    mu.center_view()
    return images_names
def slice_brain(cut_pos=None, save_image=False):
    coordinate = bpy.context.scene.cursor_location
    cut_type = bpy.context.scene.slicer_cut_type
    create_joint_brain_obj()
    # coordinate = list(D.screens['Default'].areas[3].spaces[0].cursor_location)
    optional_cut_types = ['sagital', 'coronal', 'axial']
    optional_rots = [[1.5708, 0, 1.5708], [1.5708, 0, 3.14], [0, 3.14, 0]]
    option_ind = optional_cut_types.index(cut_type)
    bpy.context.scene.is_sliced_ind = option_ind
    bpy.context.scene.last_cursor_location = coordinate
    if cut_pos is None:
        cut_pos = [0.0, 0.0, 0.0]
        cut_pos[option_ind] = coordinate[option_ind]
    print('slice_brain: cut pos {}'.format(cut_pos))
    # print('rot={}'.format(optional_rots[option_ind]))
    if bpy.data.objects.get('{}_plane'.format(cut_type)) is None:
        bpy.ops.mesh.primitive_plane_add(radius=25.7 / 2.0, location=tuple(cut_pos))
        bpy.context.object.name = '{}_plane'.format(cut_type)
        bpy.context.object.rotation_euler = optional_rots[option_ind]
        bpy.ops.mesh.uv_texture_add()
    else:
        bpy.data.objects['{}_plane'.format(cut_type)].hide = False
        bpy.data.objects['{}_plane'.format(cut_type)].hide_render = False
    optional_cut_types.remove(cut_type)
    for cut in optional_cut_types:
        if bpy.data.objects.get('{}_plane'.format(cut)):
            bpy.data.objects['{}_plane'.format(cut)].hide = True
            bpy.data.objects['{}_plane'.format(cut)].hide_render = True

    cur_plane_obj = bpy.data.objects['{}_plane'.format(cut_type)]
    cur_plane_obj.location = tuple(cut_pos)
    # images_path = '{}_{}.png'.format(bpy.context.scene.slices_modality, cut_type)
    images_path = '{}.{}'.format(cut_type, _addon().get_figure_format())
    # slice_image_path = glob.glob('{}*{}*'.format(images_path, cut_type))
    try:
        slice_image = bpy.data.images[images_path]
        print(slice_image)
        cur_plane_obj.data.uv_textures['UVMap'].data[0].image = slice_image
    except:
        pass

    if bpy.data.objects.get('masking_cube') is None:
        bpy.ops.mesh.primitive_cube_add(radius=10)
        bpy.context.object.name = 'masking_cube'
    cube_location = [0, 0, 0]
    if cut_pos[option_ind] > 0 or cut_type == 'axial':
        cube_location[option_ind] = cut_pos[option_ind] + 9.99
    elif cut_pos[option_ind] < 0:
        cube_location[option_ind] = cut_pos[option_ind] - 9.99
    bpy.data.objects['masking_cube'].location = tuple(cube_location)
    bpy.data.objects['masking_cube'].hide = True
    bpy.data.objects['masking_cube'].hide_render = True
    for hemi in ['lh', 'rh']:
        inflated_object = mu.get_hemi_obj(hemi)
        if inflated_object.modifiers.get('mask_for_slice') is None:
            inflated_object.modifiers.new('mask_for_slice', type='BOOLEAN')
        inflated_object.modifiers['mask_for_slice'].object = bpy.data.objects['masking_cube']
        inflated_object.modifiers['mask_for_slice'].operation = 'DIFFERENCE'
        inflated_object.modifiers['mask_for_slice'].double_threshold = 0
    bpy.context.scene.objects.active = cur_plane_obj
    if cur_plane_obj.modifiers.get('Boolean') is None:
        cur_plane_obj.modifiers.new('Boolean', type='BOOLEAN')
        cur_plane_obj.modifiers['Boolean'].object = bpy.data.objects['joint_brain']
        cur_plane_obj.modifiers['Boolean'].operation = 'INTERSECT'
    cur_plane_obj.hide_select = True
    if save_image:
        _addon().save_image('slicing', bpy.context.scene.save_selected_view)
Exemple #10
0
def slice_brain(cut_pos=None, save_image=False, render_image=False):
    coordinate = bpy.context.scene.cursor_location
    cut_type = bpy.context.scene.slicer_cut_type
    create_joint_brain_obj()
    # coordinate = list(D.screens['Default'].areas[3].spaces[0].cursor_location)
    optional_cut_types = ['sagital', 'coronal', 'axial']
    optional_rots = [[1.5708, 0, 1.5708], [1.5708, 0, 3.14], [0, 3.14, 0]]
    option_ind = optional_cut_types.index(cut_type)
    bpy.context.scene.is_sliced_ind = option_ind
    bpy.context.scene.last_cursor_location = coordinate
    if cut_pos is None:
        cut_pos = [0.0, 0.0, 0.0]
        cut_pos[option_ind] = coordinate[option_ind]
    print('slice_brain: cut pos {}'.format(cut_pos))
    # print('rot={}'.format(optional_rots[option_ind]))
    if bpy.data.objects.get('{}_plane'.format(cut_type)) is None:
        bpy.ops.mesh.primitive_plane_add(radius=25.7 / 2.0,
                                         location=tuple(cut_pos))
        bpy.context.object.name = '{}_plane'.format(cut_type)
        bpy.context.object.rotation_euler = optional_rots[option_ind]
        # if cut_type == 'axial':import
        #     bpy.ops.object.mode_set(mode='EDIT')
        #     bpy.ops.mesh.flip_normals()
        #     bpy.ops.object.mode_set(mode='OBJECT')
        bpy.ops.mesh.uv_texture_add()
        try:
            bpy.context.object.active_material = bpy.data.materials[
                '{}_plane_mat'.format(cut_type)]
        except:
            print('can\'t show slice on rendering mode')

    else:
        bpy.data.objects['{}_plane'.format(cut_type)].hide = False
        bpy.data.objects['{}_plane'.format(cut_type)].hide_render = False
    optional_cut_types.remove(cut_type)
    for cut in optional_cut_types:
        if bpy.data.objects.get('{}_plane'.format(cut)):
            bpy.data.objects['{}_plane'.format(cut)].hide = True
            bpy.data.objects['{}_plane'.format(cut)].hide_render = True

    cur_plane_obj = bpy.data.objects['{}_plane'.format(cut_type)]
    cur_plane_obj.location = tuple(cut_pos)
    # images_path = '{}_{}.png'.format(bpy.context.scene.slices_modality, cut_type)
    images_path = '{}.{}'.format(cut_type,
                                 _addon().get_figure_format().upper())
    # slice_image_path = glob.glob('{}*{}*'.format(images_path, cut_type))
    try:
        slice_image = bpy.data.images[images_path]
        print(slice_image)
        cur_plane_obj.data.uv_textures['UVMap'].data[0].image = slice_image
        bpy.data.materials['{}_plane_mat'.format(cut_type)].node_tree.nodes[
            'Image Texture'].image = bpy.data.images['{}.JPEG'.format(
                cut_type)]
    except:
        print(traceback.format_exc())
        print('can\'t show slice on rendering mode')

    if bpy.data.objects.get('masking_cube') is None:
        bpy.ops.mesh.primitive_cube_add(radius=10)
        bpy.context.object.name = 'masking_cube'
    cube_location = [0, 0, 0]
    # if cut_pos[option_ind] > 0 or cut_type in ['axial','coronal']:
    if bpy.context.scene.what_to_cut == '1':
        cube_location[option_ind] = cut_pos[option_ind] + 9.98
        is_coordinate_positive = True
    # elif cut_pos[option_ind] < 0:
    elif bpy.context.scene.what_to_cut == '2':
        cube_location[option_ind] = cut_pos[option_ind] - 9.98
        is_coordinate_positive = False
    bpy.data.objects['masking_cube'].location = tuple(cube_location)
    bpy.data.objects['masking_cube'].hide = True
    bpy.data.objects['masking_cube'].hide_render = True

    for hemi in ['lh', 'rh']:
        inflated_object = mu.get_hemi_obj(hemi)
        # if inflated_object.modifiers.get('mask_for_slice') is None:
        #     inflated_object.modifiers.new('mask_for_slice', type='BOOLEAN')
        # inflated_object.modifiers['mask_for_slice'].object = bpy.data.objects['masking_cube']
        # inflated_object.modifiers['mask_for_slice'].operation = 'DIFFERENCE'
        # inflated_object.modifiers['mask_for_slice'].double_threshold = 0
        mask_object_with_cube(inflated_object)
    try:
        #  TODO  Noam this is where I slice the head object.
        if bpy.context.scene.slice_seghead:
            # if we need to slice the head :
            mask_object_with_cube(bpy.data.objects['seghead'])
        else:
            # else, make sure we don't show the slicing
            bpy.data.objects['seghead'].modifiers[
                'mask_for_slice'].show_viewport = False
            bpy.data.objects['seghead'].modifiers[
                'mask_for_slice'].show_render = False

    except:
        print('outer skin object does not exist.')
    bpy.context.scene.objects.active = cur_plane_obj
    if cur_plane_obj.modifiers.get('Boolean') is None:
        cur_plane_obj.modifiers.new('Boolean', type='BOOLEAN')
        cur_plane_obj.modifiers['Boolean'].object = bpy.data.objects[
            'joint_brain']
        cur_plane_obj.modifiers['Boolean'].operation = 'INTERSECT'
    flip_slice_plane_if_needed(is_coordinate_positive)
    cur_plane_obj.hide_select = True
    if save_image:
        _addon().save_image('slicing', bpy.context.scene.save_selected_view)
    if render_image:
        _addon().render_image(set_to_camera_mode=True)
Exemple #11
0
def color_contours(specific_labels=[], specific_hemi='both', labels_contours=None, cumulate=False, change_colorbar=False,
                   specific_colors=None, atlas='', move_cursor=True, filter=''):
    if _addon() is None:
        return
    if filter != '':
        bpy.context.scene.labels_contours_filter = filter
        if isinstance(LabelsPanel.labels['rh'], np.ndarray):
            specific_labels = LabelsPanel.labels['rh'].tolist() + LabelsPanel.labels['lh'].tolist()
        else:
            specific_labels = LabelsPanel.labels['rh'] + LabelsPanel.labels['lh']
    elif isinstance(specific_labels, str):
        specific_labels = [specific_labels]
    if atlas != '' and atlas != bpy.context.scene.contours_coloring and atlas in LabelsPanel.existing_contoures:
        bpy.context.scene.contours_coloring = atlas
    if atlas == '' and bpy.context.scene.atlas in LabelsPanel.existing_contoures:
        bpy.context.scene.contours_coloring = bpy.context.scene.atlas
    if labels_contours is None:
        labels_contours = LabelsPanel.labels_contours
    contour_max = max([labels_contours[hemi]['max'] for hemi in mu.HEMIS])
    if contour_max == 0:
        print('No contours!')
        return False
    if not _addon().colorbar_values_are_locked() and change_colorbar:
        _addon().set_colormap('jet')
        _addon().set_colorbar_title('{} labels contours'.format(bpy.context.scene.contours_coloring))
        _addon().set_colorbar_max_min(contour_max, 1)
        _addon().set_colorbar_prec(0)
    _addon().show_activity()
    specific_label_ind = 0
    if specific_colors is not None:
        specific_colors = np.tile(specific_colors, (len(specific_labels), 1))
    for hemi in mu.HEMIS:
        contours = labels_contours[hemi]['contours']
        if specific_hemi != 'both' and hemi != specific_hemi:
            selected_contours = np.zeros(contours.shape) if specific_colors is None else np.zeros((contours.shape[0], 4))
        elif len(specific_labels) > 0:
            selected_contours = np.zeros(contours.shape) if specific_colors is None else np.zeros((contours.shape[0], 4))
            for specific_label in specific_labels:
                if mu.get_hemi_from_fname(specific_label) != hemi:
                    continue
                label_ind = np.where(np.array(labels_contours[hemi]['labels']) == specific_label)
                if len(label_ind) > 0 and len(label_ind[0]) > 0:
                    label_ind = label_ind[0][0]
                    selected_contours[np.where(contours == label_ind + 1)] = \
                        label_ind + 1 if specific_colors is None else [1, *specific_colors[specific_label_ind]]
                    specific_label_ind += 1
                    if move_cursor and len(specific_labels) == 1 and 'centers' in labels_contours[hemi]:
                        vert = labels_contours[hemi]['centers'][label_ind]
                        _addon().move_cursor_according_to_vert(vert, 'inflated_{}'.format(hemi))
                        _addon().set_closest_vertex_and_mesh_to_cursor(vert, 'inflated_{}'.format(hemi))
                        _addon().create_slices()
                        _addon().snap_cursor(True)
                        _addon().set_tkreg_ras(bpy.context.scene.cursor_location * 10, False)
                else:
                    print("Can't find {} in the labels contours!".format(specific_label))
        else:
            selected_contours = labels_contours[hemi]['contours']
        mesh = mu.get_hemi_obj(hemi).data
        mesh.vertex_colors.active_index = mesh.vertex_colors.keys().index('contours')
        mesh.vertex_colors['contours'].active_render = True
        # Saving the labels names and RGB values
        unique_values = np.unique(contours)
        contours_colors = _addon().coloring.calc_colors(unique_values, 0, 256 / contour_max)
        contours_labels_info = np.column_stack((labels_contours[hemi]['labels'], contours_colors[1:, :]))
        output_fname = op.join(mu.get_user_fol(), 'labels',  '{}_{}_{}_labels_names_and_colors.csv'.format(
            bpy.context.scene.contours_coloring, hemi, _addon().colorbar.get_colormap_name()))
        np.savetxt(output_fname, contours_labels_info, ('%s', '%s', '%s', '%s'), ',')
        print('Saving labels names and RGB values to {}'.format(output_fname))
        # Color the hemi surface
        _addon().color_hemi_data(
            hemi, selected_contours, 0.1, 256 / contour_max, override_current_mat=not cumulate,
            coloring_layer='contours', check_valid_verts=False)

    _addon().what_is_colored().add(_addon().WIC_CONTOURS)