コード例 #1
0
def One_Key_Frame_Graphs(
        data_folder,
        sub_dic,
        show_clip=3,
        alinged_sub_folder=r'\Results\Final_Aligned_Frames',
        Stim_Align_sub_folder=r'\Results\Stim_Frame_Align.pkl'):
    result_folder = data_folder + r'\Results'
    graph_save_folder = result_folder + r'\Only_Frame_SubGraphs'
    OS_Tools.mkdir(result_folder)
    OS_Tools.mkdir(graph_save_folder)
    stim_path = data_folder + Stim_Align_sub_folder
    stim_dic = OS_Tools.Load_Variable(stim_path)
    all_tif_name = OS_Tools.Get_File_Name(data_folder + alinged_sub_folder)
    graph_num = len(sub_dic)
    all_sub_graph_names = list(sub_dic.keys())
    for i in range(graph_num):
        current_name = all_sub_graph_names[i]
        current_a = Frame_ID_Extractor(stim_dic, sub_dic[current_name][0])
        current_b = Frame_ID_Extractor(stim_dic, sub_dic[current_name][1])
        current_sub_graph, current_t_graph, current_info_dic = Single_Subgraph_Generator(
            all_tif_name, current_a, current_b)
        current_sub_graph = Graph_Tools.Clip_And_Normalize(
            current_sub_graph, show_clip)
        current_t_graph = Graph_Tools.Clip_And_Normalize(
            current_t_graph, show_clip)
        # Save graphs
        Graph_Tools.Show_Graph(current_sub_graph, current_name + '_Sub_Graph',
                               graph_save_folder)
        Graph_Tools.Show_Graph(current_t_graph, current_name + '_t_Graph',
                               graph_save_folder)
        OS_Tools.Save_Variable(graph_save_folder, current_name + r'_Sub_Info',
                               current_info_dic, '.info')
    return True
コード例 #2
0
 def __init__(self,all_folders):
     
     self.all_folders = all_folders
     self.all_save_folders = List_Op.List_Annex(self.all_folders,['Results'])
     self.Aligned_frame_folders = List_Op.List_Annex(self.all_save_folders,['Aligned_Frames'])
     for i in range(len(self.all_save_folders)):
         OS_Tools.mkdir(self.all_save_folders[i])
         OS_Tools.mkdir(self.Aligned_frame_folders[i])
     self.Before_Align_Tif_Name = []
     for i in range(len(self.all_folders)):
         current_run_tif = OS_Tools.Get_File_Name(self.all_folders[i])
         self.Before_Align_Tif_Name.append(current_run_tif)
コード例 #3
0
def Translation_Alignment(all_folders,
                          base_mode='global',
                          input_base=np.array([[0, 0], [0, 0]]),
                          align_range=20,
                          align_boulder=20,
                          before_average=True,
                          average_std=5,
                          big_memory_mode=False,
                          save_aligned_data=False,
                          graph_shape=(512, 512),
                          timer=True):
    '''
    
    This function will align all tif graphs in input folders. Only translation transaction here. Affine transformation need further discussion.
    
    Parameters
    ----------
    all_folders:(list)
        List of all tif folders, elements are strs.
    
    base_mode:('global',int,'input',optional. The default is 'global')
        How to select base frame. 'global': use global average as base. int: use average of specific run as base. 'input':Manually input base graph, need to be a 2D-Ndarray.
        
    input_base:(2D-Ndarray,optional. The default is none.)
        If base_mode = 'input', input_base must be given. This will be the base for alignment.
        
    align_range:(int,optional. The default is 20)
        Max pixel of alignment. 
        
    align_boulder:(int,optional. The default is 20)
        boulder cut for align. For different graph size, this variable shall be change.
        
    before_average:(bool,optional. The default is True)
        Whether before average is done. It can be set False to save time, on this case base graph shall be given.
        
    average_std:(float,optional. The default is 5)
        How much std you want for average graph generation. Different std can effect graph effect.
    
    big_memory_mode:(bool,optional. The default is False)
        If memory is big enough, use this mode is faster.
        
    save_aligned_data:(bool,optional. The default is False)
        Can be true only in big memory mode. This will save all aligned graph in a single 4D-Ndarray file.Save folder is the first folder.
        
    graph_shape:(2-element-turple,optional. The default is (512,512))
        Shape of graphs. All input graph must be in same shape.
        
    timer:(bool,optional. The default is True)
        Show runtime of function and each procedures.
    
        
    Returns
    -------
    bool
        Whether new folder is generated.
    
    '''
    time_tic_start = time.time()
    #%% Step1, generate folders and file cycle.
    all_save_folders = List_Op.List_Annex(all_folders, ['Results'])
    Aligned_frame_folders = List_Op.List_Annex(all_save_folders,
                                               ['Aligned_Frames'])
    for i in range(len(all_save_folders)):
        OS_Tools.mkdir(all_save_folders[i])
        OS_Tools.mkdir(Aligned_frame_folders[i])
    Before_Align_Tif_Name = []
    for i in range(len(all_folders)):
        current_run_tif = OS_Tools.Get_File_Name(all_folders[i])
        Before_Align_Tif_Name.append(current_run_tif)

    #%% Step2, Generate average map before align.
    if before_average == True:
        print('Before run averaging ...')
        Before_Align_Dics = {
        }  # This is the dictionary of all run averages. Keys are run id.
        total_graph_num = 0  # Counter of graph numbers.
        for i in range(len(Before_Align_Tif_Name)):
            current_run_graph_num = len(Before_Align_Tif_Name[i])
            total_graph_num += current_run_graph_num
            current_run_average = Graph_Tools.Average_From_File(
                Before_Align_Tif_Name[i])
            current_run_average = Graph_Tools.Clip_And_Normalize(
                current_run_average, clip_std=average_std)
            Before_Align_Dics[i] = (
                current_run_average, current_run_graph_num
            )  # Attention here, data recorded as turple.
            Graph_Tools.Show_Graph(
                current_run_average, 'Run_Average',
                all_save_folders[i])  # Show and save Run Average.
        # Then Use Weighted average method to generate global tif.
        global_average_graph = np.zeros(shape=np.shape(
            Before_Align_Dics[0][0]),
                                        dtype='f8')  # Base on shape of graph
        for i in range(len(Before_Align_Tif_Name)):
            global_average_graph += Before_Align_Dics[i][0].astype(
                'f8') * Before_Align_Dics[i][1] / total_graph_num
        global_average_graph = Graph_Tools.Clip_And_Normalize(
            global_average_graph, clip_std=average_std)
        # Then save global average in each run folder.
        if len(all_folders) > 1:
            for i in range(len(Before_Align_Tif_Name)):
                Graph_Tools.Show_Graph(global_average_graph,
                                       'Global_Average',
                                       all_save_folders[i],
                                       show_time=0)
        else:
            print('Only One run, no global average.')
    else:
        print('Before average Skipped.')
    time_tic_average0 = time.time()

    #%% Step3, Core Align Function.
    print('Aligning...')
    if base_mode == 'global':
        base = global_average_graph
    elif base_mode == 'input':
        base = input_base
    elif type(base_mode) == int:
        base = Before_Align_Dics[base_mode][0]
    else:
        raise IOError('Invalid base mode.')
    # In big memory mode, save aligned_data in a dictionary file.
    if big_memory_mode == True:
        All_Aligned_Frame = {}
        for i in range(len(Before_Align_Tif_Name)):
            All_Aligned_Frame[i] = np.zeros(
                shape=(graph_shape + (len(Before_Align_Tif_Name[i]), )),
                dtype='u2')  # Generate empty graph matrix.
    for i in range(len(Before_Align_Tif_Name)):  # Cycle all runs
        for j in range(len(
                Before_Align_Tif_Name[i])):  # Cycle all graphs in current run
            current_graph = cv2.imread(Before_Align_Tif_Name[i][j],
                                       -1)  # Read in current graph.
            _, _, current_aligned_graph = Alignment(base,
                                                    current_graph,
                                                    boulder=align_boulder,
                                                    align_range=align_range)
            graph_name = Before_Align_Tif_Name[i][j].split(
                '\\')[-1][:-4]  # Ignore extend name'.tif'.
            Graph_Tools.Show_Graph(current_aligned_graph,
                                   graph_name,
                                   Aligned_frame_folders[i],
                                   show_time=0)
            if big_memory_mode == True:
                All_Aligned_Frame[i][:, :, j] = current_aligned_graph
    print('Align Finished, generating average graphs...')
    time_tic_align_finish = time.time()

    #%% Step4, After Align Average
    After_Align_Graphs = {}
    if big_memory_mode == True:  # Average can be faster.
        temp_global_average_after_align = np.zeros(shape=graph_shape,
                                                   dtype='f8')
        for i in range(len(All_Aligned_Frame)):
            current_run_average = Graph_Tools.Clip_And_Normalize(
                np.mean(All_Aligned_Frame[i], axis=2),
                clip_std=average_std)  # Average run graphs, in type 'u2'
            After_Align_Graphs[i] = (current_run_average,
                                     len(All_Aligned_Frame[i][0, 0, :]))
            temp_global_average_after_align += After_Align_Graphs[i][0].astype(
                'f8') * After_Align_Graphs[i][1] / total_graph_num
        global_average_after_align = Graph_Tools.Clip_And_Normalize(
            temp_global_average_after_align, clip_std=average_std)
    else:  # Traditional ways.
        temp_global_average_after_align = np.zeros(shape=graph_shape,
                                                   dtype='f8')
        for i in range(len(Aligned_frame_folders)):
            current_run_names = OS_Tools.Get_File_Name(
                Aligned_frame_folders[i])
            current_run_average = Graph_Tools.Average_From_File(
                current_run_names)
            current_run_average = Graph_Tools.Clip_And_Normalize(
                current_run_average, clip_std=average_std)
            After_Align_Graphs[i] = (current_run_average,
                                     len(current_run_names))
            temp_global_average_after_align += After_Align_Graphs[i][0].astype(
                'f8') * After_Align_Graphs[i][1] / total_graph_num
        global_average_after_align = Graph_Tools.Clip_And_Normalize(
            temp_global_average_after_align, clip_std=average_std)
    # After average, save aligned graph in each save folder.
    for i in range(len(all_save_folders)):
        current_save_folder = all_save_folders[i]
        Graph_Tools.Show_Graph(After_Align_Graphs[i][0],
                               'Run_Average_After_Align', current_save_folder)
        if i == 0:  # Show global average only once.
            global_show_time = 5000
        else:
            global_show_time = 0
        if len(all_folders) > 1:
            Graph_Tools.Show_Graph(global_average_after_align,
                                   'Global_Average_After_Align',
                                   current_save_folder,
                                   show_time=global_show_time)
    time_tic_average1 = time.time()

    #%% Step5, save and timer
    if save_aligned_data == True:
        OS_Tools.Save_Variable(all_save_folders[0], 'All_Aligned_Frame_Data',
                               All_Aligned_Frame)

    if timer == True:
        whole_time = time_tic_average1 - time_tic_start
        before_average_time = time_tic_average0 - time_tic_start
        align_time = time_tic_align_finish - time_tic_average0
        after_average_time = time_tic_average1 - time_tic_align_finish
        print('Total Time = ' + str(whole_time) + ' s.')
        print('Before Average Time = ' + str(before_average_time) + ' s.')
        print('Align Time = ' + str(align_time) + ' s.')
        print('After Average Time = ' + str(after_average_time) + ' s.')

    return True
コード例 #4
0
def Tremble_Comparision(before_folder,
                        after_folder,
                        boulder_ignore=20,
                        cut_shape=(9, 9),
                        mask_thres=0):
    # Initialization
    save_folder = after_folder + r'\Results'
    OS_Tools.mkdir(save_folder)
    save_folder = save_folder + r'\Tremble_Compare'
    OS_Tools.mkdir(save_folder)
    row_num = cut_shape[0]
    col_num = cut_shape[1]
    frac_num = row_num * col_num
    cov_matrix_dic = {}
    var_matrix_dic = {}
    variation = np.zeros(shape=(row_num, col_num, 2), dtype='f8')
    variation_change = np.zeros(shape=(row_num, col_num), dtype='f8')
    variation_prop = np.zeros(shape=(row_num, col_num), dtype='f8')
    # Calculation Begins
    before_schematic, before_frac_center = Tremble_Evaluator(
        before_folder,
        boulder_ignore=boulder_ignore,
        cut_shape=cut_shape,
        mask_thres=mask_thres)
    after_schematic, after_frac_center = Tremble_Evaluator(
        after_folder,
        boulder_ignore=boulder_ignore,
        cut_shape=cut_shape,
        mask_thres=mask_thres)
    fig, ax = plt.subplots(row_num, col_num,
                           figsize=(30, 28))  # Initialize graphs
    fig.suptitle('Mass Center Distribution', fontsize=54)
    # Cycle all fracture,get scatter map and variance
    for i in range(frac_num):
        # Graph_Plot
        current_row = i % row_num
        current_col = i // row_num
        ax[current_row, current_col].scatter(before_frac_center[i, :, 1],
                                             before_frac_center[i, :, 0],
                                             s=1,
                                             c='r')
        ax[current_row, current_col].scatter(after_frac_center[i, :, 1],
                                             after_frac_center[i, :, 0],
                                             s=1,
                                             c='g')
        # After plot, calculate cov matrix and variance.
        before_cov = np.cov(before_frac_center[i, :, :].T)
        after_cov = np.cov(after_frac_center[i, :, :].T)
        cov_matrix_dic[i] = (before_cov, after_cov)
        before_eig, _ = np.linalg.eig(before_cov)
        after_eig, _ = np.linalg.eig(after_cov)
        before_var = np.round(before_eig.sum(), 4)
        after_var = np.round(after_eig.sum(), 4)
        variation[current_row, current_col, 0] = before_var
        variation[current_row, current_col, 1] = after_var
        variation_change[current_row, current_col] = before_var - after_var
        variation_prop[current_row,
                       current_col] = (before_var - after_var) / before_var
        # Text annotate
        anchored_text = AnchoredText('Before variance:' + str(before_var) +
                                     '\n After variance:' + str(after_var),
                                     loc='lower left')
        ax[current_row, current_col].add_artist(anchored_text)

    # After this, save figures and matrixs.
    var_matrix_dic['Before'] = variation[:, :, 0]
    var_matrix_dic['After'] = variation[:, :, 1]
    Graph_Tools.Show_Graph(before_schematic, 'Before_Schematic', save_folder)
    Graph_Tools.Show_Graph(after_schematic, 'After_Schematic', save_folder)
    fig.savefig(save_folder + '\Scatter Plots.png', dpi=330)
    OS_Tools.Save_Variable(save_folder, 'cov_matrix', cov_matrix_dic)
    OS_Tools.Save_Variable(save_folder, 'variance_matrix', var_matrix_dic)
    # Calculate variance change and plot variance map.
    # Before variance map
    plt.clf()
    fig2 = plt.figure(figsize=(15, 15))
    plt.title('Before Align Variance', fontsize=36)
    fig2 = sns.heatmap(variation[:, :, 0],
                       cmap='bwr',
                       annot=True,
                       annot_kws={"size": 20},
                       square=True,
                       yticklabels=False,
                       xticklabels=False,
                       center=0)
    fig2.figure.savefig(save_folder + '\Before_Variance.png', dpi=330)
    # After variance map
    plt.clf()
    fig2 = plt.figure(figsize=(15, 15))
    plt.title('After Align Variance', fontsize=36)
    fig2 = sns.heatmap(variation[:, :, 1],
                       cmap='bwr',
                       annot=True,
                       annot_kws={"size": 20},
                       square=True,
                       yticklabels=False,
                       xticklabels=False,
                       center=0)
    fig2.figure.savefig(save_folder + '\After_Variance.png', dpi=330)
    # Variance change map
    plt.clf()
    fig2 = plt.figure(figsize=(15, 15))
    plt.title('Variance Change', fontsize=36)
    fig2 = sns.heatmap(variation_change,
                       cmap='bwr',
                       annot=True,
                       annot_kws={"size": 20},
                       square=True,
                       yticklabels=False,
                       xticklabels=False,
                       center=0)
    fig2.figure.savefig(save_folder + '\Variance_Change.png', dpi=330)
    # Variance change propotion map
    plt.clf()
    fig2 = plt.figure(figsize=(15, 15))
    plt.title('Variance Change Propotion', fontsize=36)
    fig2 = sns.heatmap(variation_prop,
                       cmap='bwr',
                       annot=True,
                       annot_kws={"size": 20},
                       square=True,
                       yticklabels=False,
                       xticklabels=False,
                       center=0)
    fig2.figure.savefig(save_folder + '\Variance_Change_Prop.png', dpi=330)
    return cov_matrix_dic, var_matrix_dic
コード例 #5
0
import My_Wheels.OS_Tools_Kit as OS_Tools
import cv2
data_folder = [r'E:\Test_Data\2P\201222_L76_2P']
run_list = [
    '1-001',  # Spon
    '1-008',  # OD
    '1-010',  # G8
    '1-011',  # RGLum4
    '1-014'  # Spon After
]
all_runs = List_Tools.List_Annex(data_folder, run_list)
#%% Add 3 list for run01 to fit ROI change.
run_1 = all_runs[0]
run1_all_tif = OS_Tools.Get_File_Name(run_1)
save_path = run_1 + r'\shape_extended'
OS_Tools.mkdir(save_path)
for i in range(len(run1_all_tif)):
    current_graph = cv2.imread(run1_all_tif[i], -1)
    extended_graph = Graph_Tools.Boulder_Extend(
        current_graph, [0, 0, 0, 3])  # 3 pix on the right.
    current_graph_name = run1_all_tif[i].split('\\')[-1]
    Graph_Tools.Show_Graph(extended_graph,
                           current_graph_name,
                           save_path,
                           show_time=0)
#%% Then align Run01_Spon.
from My_Wheels.Translation_Align_Function import Translation_Alignment
Translation_Alignment([all_runs[0] + r'\shape_extended'],
                      graph_shape=(325, 324))
#%% Then Use this base to align other runs.
base = cv2.imread(
コード例 #6
0
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 30 14:37:51 2021

@author: ZR
"""

from My_Wheels.Standard_Parameters.Stim_Name_Tools import Stim_ID_Combiner
from My_Wheels.Cell_Processor import Cell_Processor
import My_Wheels.OS_Tools_Kit as ot
import matplotlib.pyplot as plt

day_folder = r'K:\Test_Data\2P\210320_L76_2P'
save_folder = day_folder + r'\_All_Results'
ot.mkdir(save_folder)
#%% Analyze Run05-G16 First.
G16_CP = Cell_Processor(day_folder, 'Run005')
all_cell_name = G16_CP.all_cell_names
Ori_IDs = Stim_ID_Combiner('G16_Oriens')
sub_sf = save_folder + r'\G16_Oriens'
ot.mkdir(sub_sf)
for i in range(len(all_cell_name)):
    _, raw_data, _ = G16_CP.Single_Cell_Response_Data(Ori_IDs,
                                                      all_cell_name[i])
    ot.Save_Variable(sub_sf, all_cell_name[i], raw_data, '.raw')
    test_fig = G16_CP.Average_Response_Map()
    test_fig.savefig(sub_sf + r'\\' + all_cell_name[i] + '_Response.png',
                     dpi=180)
    plt.clf()
#%% Then directions
Dir_IDs = Stim_ID_Combiner('G16_Dirs')
コード例 #7
0
def Standard_Stim_Processor(data_folder,
                            stim_folder,
                            sub_dic,
                            alinged_sub_folder=r'\Results\Aligned_Frames',
                            show_clip=3,
                            tuning_graph=False,
                            cell_method='Default',
                            filter_method='Gaussian',
                            LP_Para=((5, 5), 1.5),
                            HP_Para=False,
                            spike_train_path='Default',
                            spike_train_filter_para=(False, False),
                            spike_train_filter_method=False):
    '''
    Generate subtraction graph, cell graph and tuning graphs if requred.

    Parameters
    ----------
    data_folder : (str)
        Run folder.
    stim_folder : (str)
        Stim file folder or Frame_Stim_Align File folder. Pre align is advised.
    sub_dic : (Dic)
        Subtraction dicionary. This can be generated from My_Wheels.Standard_Parameters
    show_clip : (float), optional
        Clip of graph show. The default is 3.
    tuning_graph : (bool), optional
        Whether we generate tuning graph of each cells. The default is False.
    cell_method : (str), optional
        Cell find method. You can input cell file path here. The default is 'Default'.
    filter_method : (str), optional
        False to skip filter. Kernel function of graph filtering. The default is 'Gaussian'.
    LP_Para : (turple), optional
        False to skip. Low pass filter of graph. The default is ((5,5),1.5).
    HP_Para : (turple), optional
        False to skip. High pass filter of graph. Big HP can be very slow!. The default is False.
    spike_train_path : (str), optional
        Path of spike train.'Default' will generate spike train directly. The default is 'Default'.
    spike_train_filter_para : (turple), optional
        Signal filter bandpass propotion of spike train. Please be sure if you need this. The default is (False,False).
    spike_train_filter_method : (str), optional
        False to skip. Method of signal filtering. The default is False.

    Returns
    -------
    None.

    '''
    # Path Cycle.
    from Cell_Find_From_Graph import On_Off_Cell_Finder
    work_folder = data_folder + r'\Results'
    OS_Tools.mkdir(work_folder)
    aligned_frame_folder = data_folder + alinged_sub_folder
    OS_Tools.mkdir(aligned_frame_folder)

    # Step1, align graphs. If already aligned, just read
    if not os.listdir(aligned_frame_folder):  # if this is a new folder
        print('Aligned data not found. Aligning here..')
        Translation_Alignment([data_folder])
    aligned_all_tif_name = np.array(
        OS_Tools.Get_File_Name(aligned_frame_folder)
    )  # Use numpy array, this is easier for slice.

    # Step2, get stim fram align matrix. If already aligned, just read in aligned dictionary.
    file_detector = len(stim_folder.split('.'))
    if file_detector == 1:  # Which means input is a folder
        print('Frame Stim not Aligned, aligning here...')
        from My_Wheels.Stim_Frame_Align import Stim_Frame_Align
        _, Frame_Stim_Dic = Stim_Frame_Align(stim_folder)
    else:  # Input is a file
        Frame_Stim_Dic = OS_Tools.Load_Variable(stim_folder)

    # Step3, get cell information
    if cell_method == 'Default':  # meaning we will use On-Off graph to find cell.
        print('Cell information not found. Finding here..')
        cell_dic = On_Off_Cell_Finder(aligned_all_tif_name,
                                      Frame_Stim_Dic,
                                      filter_method=filter_method,
                                      LP_Para=LP_Para,
                                      HP_Para=HP_Para)
    else:
        cell_dic = OS_Tools.Load_Variable(cell_method)

    # Step4, calculate spike_train.
    if spike_train_path != 'Default':
        dF_F_train = OS_Tools.Load_Variable(spike_train_path)
    else:  # meaning we need to calculate spike train from the very begining.

        _, dF_F_train = Spike_Train_Generator(
            aligned_all_tif_name,
            cell_dic['All_Cell_Information'],
            Base_F_type='nearest_0',
            stim_train=Frame_Stim_Dic['Original_Stim_Train'],
            LP_Para=LP_Para,
            HP_Para=HP_Para,
            filter_method=filter_method)
    #Step5, filt spike trains.
    if spike_train_filter_method != False:  # Meaning we need to do train filter.
        for i in range(len(dF_F_train)):
            dF_F_train[i] = My_Filter.Signal_Filter(dF_F_train,
                                                    spike_train_filter_method,
                                                    spike_train_filter_para)
    # Step6, get each frame graph and cell graph.
    all_graph_keys = list(sub_dic.keys())
    for i in range(len(sub_dic)):
        output_folder = work_folder + r'\Subtraction_Graphs'
        current_key = all_graph_keys[i]
        current_sub_list = sub_dic[current_key]
        A_conds = current_sub_list[0]  # condition of A graph
        B_conds = current_sub_list[1]  # condition of B graph
        A_IDs = []
        B_IDs = []
        for i in range(len(A_conds)):
            A_IDs.extend(Frame_Stim_Dic[A_conds[i]])
        for i in range(len(B_conds)):
            B_IDs.extend(Frame_Stim_Dic[B_conds[i]])
        # Get frame maps.
        current_sub_graph, current_t_graph, current_F_info = Single_Subgraph_Generator(
            aligned_all_tif_name, A_IDs, B_IDs, filter_method, LP_Para,
            HP_Para)

        current_sub_graph = Graph_Tools.Clip_And_Normalize(
            current_sub_graph, show_clip)
        Graph_Tools.Show_Graph(current_sub_graph, current_key + '_SubGraph',
                               output_folder)
        current_t_graph = Graph_Tools.Clip_And_Normalize(
            current_t_graph, show_clip)
        Graph_Tools.Show_Graph(current_t_graph, current_key + '_T_Graph',
                               output_folder)
        OS_Tools.Save_Variable(output_folder,
                               current_key + '_Sub_Info',
                               current_F_info,
                               extend_name='.info')
        # Get cell maps
        cell_info = cell_dic['All_Cell_Information']
        current_cell_sub_graph, current_cell_t_graph, current_cell_info = Single_Cellgraph_Generator(
            dF_F_train, cell_info, show_clip, A_IDs, B_IDs)
        Graph_Tools.Show_Graph(current_cell_sub_graph,
                               current_key + '_Cell_SubGraph', output_folder)
        Graph_Tools.Show_Graph(current_cell_t_graph,
                               current_key + '_Cell_T_Graph', output_folder)
        OS_Tools.Save_Variable(output_folder,
                               current_key + '_Cell_Info',
                               current_cell_info,
                               extend_name='.info')
    #Step7, calculate cell tuning graph.
    if tuning_graph == True:
        print('Not finished yet.')
コード例 #8
0
def Affine_Aligner_Gaussian(data_folder,
                            base_graph,
                            window_size=1,
                            max_point=50000,
                            good_match_prop=0.3,
                            dist_lim=120,
                            match_checker=1,
                            sector_num=4,
                            write_file=False,
                            save_folder='Default'):
    if save_folder == 'Default':
        save_folder = data_folder + r'\Results'
    aligned_tif_folder = save_folder + r'\Affined_Frames'
    OS_Tools.mkdir(save_folder)
    OS_Tools.mkdir(aligned_tif_folder)

    all_tif_name = OS_Tools.Get_File_Name(data_folder)
    graph_num = len(all_tif_name)
    graph_shape = cv2.imread(all_tif_name[0], -1).shape
    height, width = graph_shape
    origin_tif_matrix = np.zeros(shape=graph_shape + (graph_num, ), dtype='u2')
    # Read in all tif name.
    for i in range(graph_num):
        origin_tif_matrix[:, :, i] = cv2.imread(all_tif_name[i], -1)
    # Then get window slipped average graph.
    if window_size == 1:
        slipped_average_matrix = origin_tif_matrix
    else:
        slipped_average_matrix = Filters.Window_Average(
            origin_tif_matrix, window_size=window_size)
    # Use slip average to get deformation parameters.
    aligned_tif_matrix = np.zeros(shape=origin_tif_matrix.shape, dtype='u2')
    h_dic = {}  # Deformation parameters
    for i in range(graph_num):
        target = slipped_average_matrix[:, :, i]
        _, current_h = Affine_Core_Point_Equal(target,
                                               base_graph,
                                               max_point=max_point,
                                               good_match_prop=good_match_prop,
                                               sector_num=sector_num,
                                               dist_lim=dist_lim,
                                               match_checker=match_checker)
        h_dic[i] = current_h
        current_deformed_graph = cv2.warpPerspective(
            origin_tif_matrix[:, :, i], current_h, (width, height))
        Graph_Tools.Show_Graph(current_deformed_graph,
                               all_tif_name[i].split('\\')[-1],
                               aligned_tif_folder,
                               show_time=0,
                               graph_formation='')
        aligned_tif_matrix[:, :, i] = current_deformed_graph
    OS_Tools.Save_Variable(save_folder, 'Deform_H', h_dic)
    if write_file == True:
        OS_Tools.Save_Variable(save_folder, 'Affine_Aligned_Graphs',
                               aligned_tif_matrix)
    # At last, generate average graphs
    graph_before_align = origin_tif_matrix.mean(axis=2).astype('u2')
    graph_after_align = aligned_tif_matrix.mean(axis=2).astype('u2')
    graph_before_align = Graph_Tools.Clip_And_Normalize(graph_before_align,
                                                        clip_std=5)
    graph_after_align = Graph_Tools.Clip_And_Normalize(graph_after_align,
                                                       clip_std=5)
    Graph_Tools.Show_Graph(graph_before_align, 'Graph_Before_Affine',
                           save_folder)
    Graph_Tools.Show_Graph(graph_after_align, 'Graph_After_Affine',
                           save_folder)
    return True