def module_main(ctx): try: #Inizialization tstart = time.process_time() print(SEPARATOR) print('Thresholding started!') #Create Image object img = a3.inputs['Input Image'] print('Thresholding: ' + img.metadata['Name']) #Get method and mode. Get kwargs if method is manual method = METHODS[a3.inputs['Method'][-1]] if method == 'Manual': kwargs = {'lower': 0, 'upper': a3.inputs['Manual threshold value']} elif method == 'None': method = 'Manual' kwargs = {'lower': 0, 'upper': 0} else: kwargs = {} if a3.inputs['Slice/Stack histogram']: kwargs['mode'] = 'Stack' else: kwargs['mode'] = 'Slice' print('Mode: ' + kwargs['mode']) print('Method: ' + method) #Run thresholding output_img, log_text = module_threshold(img, method, kwargs) threshold_value = str(log_text.split('\n')[-1].split(':')[-1]) print('Threshold value(s): ' + threshold_value) #Change Name in metadata output_img.metadata['Name'] = img.metadata['Name'] + '_auto_thr' if (a3.inputs['Save Threshold(s)'] or a3.inputs['Save Image']): #Set path and filename #Generate base directory if os.path.isdir(a3.inputs['Output Path'].path): output_path = a3.inputs['Output Path'].path else: output_path = os.path.dirname(a3.inputs['File Path'].path) #Create otput directory output_path = os.path.join(output_path, 'Thresholding') if not os.path.exists(output_path): os.makedirs(output_path) #Save threshold in file if a3.inputs['Save Threshold(s)']: print('Saving Threshold Values to file!') channel_name = img.metadata['Name'] filename = a3.inputs['File Path'].path print( '#########################################################################' ) print(threshold_value) threshold_to_text(output_path, filename, channel_name, method, threshold_value) #Save images #Generate output filename base for images filename_img = os.path.basename(output_img.metadata['Path']) basename_img = os.path.splitext(filename_img)[0] if a3.inputs['Save Image']: print('Saving output images!') #image_list=[ch1_img, ch2_img, ovl_img] name_img = basename_img + '_{}_{}.ome.tiff'.format( str(method), str(kwargs['mode'])) save_image(output_img, output_path, name_img) #Set output a3.outputs['Thresholded Image'] = output_img #Finalization tstop = time.process_time() print('Processing finished in ' + str((tstop - tstart)) + ' seconds!') print('Autothresholding was successfully!') print(SEPARATOR) except Exception as e: raise error("Error occured while executing '" + str(ctx.type()) + "' module '" + str(ctx.name()) + "' !", exception=e)
def module_main(ctx, methods=meth_list): try: #Get file name and output path. If "Output Path" is not set or does not exist use "File Path". file_name = a3.inputs['File Path'].path if os.path.isdir(a3.inputs['Output Path'].path): out_path = a3.inputs['Output Path'].path else: out_path = os.path.join(os.path.dirname(file_name), 'Output') out_file_path = os.path.join(out_path, 'Thresholder_results.xlsx') #Create output directory if does not exist if not os.path.exists(out_path): os.makedirs(out_path) #If excel file with results from previos run or previous batch steps #load as dataframe if not os.path.exists(out_file_path) or not os.path.isfile( out_file_path): results = pd.DataFrame() else: results = pd.read_excel(out_file_path, 0) #Run threshold #Get method and mode. Get kwargs if method is manual method = methods[a3.inputs['Method'][-1]] if method == 'Manual': kwargs = {'lower': 0, 'upper': a3.inputs['Manual Threshold Value']} elif method == 'None': method = 'Manual' kwargs = {'lower': 0, 'upper': 0} else: kwargs = {} if a3.inputs['Slice/Stack Histogram']: kwargs['mode'] = 'Stack' else: kwargs['mode'] = 'Slice' results_dict = {} if method == 'All': methods.remove('All') else: methods = [method] #Analyze raw image parameters raw_data = core.analyze_raw(a3.inputs['Image']) #Create ordered dict for results and run analysis results_dict = OrderedDict() results_dict['File'] = os.path.basename(file_name) for keys in raw_data.keys(): results_dict[keys] = raw_data[keys] for meth in methods: image_thresholded, thr_value = core.threshold( a3.inputs['Image'], meth, **kwargs) if a3.inputs['Save Images']: save_image( [image_thresholded], out_path, str( os.path.splitext(os.path.basename(file_name))[0] + '_' + str(meth) + '.tif')) if kwargs['mode'] == 'Slice': print('Thresholds using ' + str(meth) + ':') print('Slice thresholds: ', thr_value) thr_value = np.mean(thr_value) print('Mean threshold: ', thr_value) if kwargs['mode'] == 'Stack': print('Threshold using ' + str(meth) + ': ', thr_value) print('') results_dict[meth] = thr_value #Append results_dict to dataframe and save results = results.append(pd.DataFrame(results_dict, index=[0])) writer = pd.ExcelWriter(out_file_path, engine='xlsxwriter') results.to_excel(writer, index=False, sheet_name='Thresholds') writer.save() except Exception as e: raise error("Error occured while executing '" + str(ctx.type()) + "' module '" + str(ctx.name()) + "' !", exception=e)
def colocalize(ch1_img, ch2_img, ovl_settings, path, show=True, to_text=False, remove_filtered=False): tagged_img_list = [ch1_img, ch2_img] #Gennerate list of names without duplicates and change 'Name' field in image metadata name_list = rename_duplicates( [x.metadata['Name'] for x in tagged_img_list]) for idx, value in enumerate(name_list): tagged_img_list[idx].metadata['Name'] = name_list[idx] print('Processing the following channels: ' + str([img.metadata['Name'] for img in tagged_img_list])) print('Filter settings: ' + str(ovl_settings)) #Run colocaliyation analysis ovl_img, _ = colocalization(tagged_img_list, overlapping_filter=ovl_settings, remove_filtered=remove_filtered) #Run filtering steps #ch1_img, _ =apply_filter(ch1_img, ch1_settings, overwrite=False, remove_filtered=False) #ch2_img, _ =apply_filter(ch2_img, ch2_settings, overwrite=False, remove_filtered=False) #Print number of objects to logText print('Number of Overlapping Objects: ' + str(len(ovl_img.database['tag']))) #Set path and filename output_path = os.path.join(path, 'Output') if not os.path.exists(output_path): os.makedirs(output_path) #Generate output filename filename_1 = os.path.basename(ch1_img.metadata['Path']) filename_2 = os.path.basename(ch2_img.metadata['Path']) if filename_1 != filename_2: basename = os.path.splitext(filename_1)[0] + '_' + os.path.splitext( filename_2)[0] else: basename = os.path.splitext(filename_1)[0] #Save data and give output path print('Saving object dataBases!') data_basename = basename + '_' + ch1_img.metadata[ 'Name'] + '_' + ch2_img.metadata['Name'] #Get extension if to_text == True: extension = ".txt" else: extension = ".xlsx" #If filename exists generate a neme that is not used file_name = get_next_filename(output_path, data_basename + extension) #If filename exists issue warning if file_name != data_basename + extension: warning('Warning: Filename already exists!! Data will be saved to ' + file_name) #Save to file save_data([ch1_img, ch2_img, ovl_img], path=output_path, file_name=os.path.splitext(file_name)[0], to_text=to_text) #Save images print('Saving output images!') image_list = [ch1_img, ch2_img, ovl_img] name_img = basename + '_{}_{}.ome.tiff'.format(ch1_img.metadata['Name'], ch2_img.metadata['Name']) save_image(image_list, output_path, name_img) return ovl_img, ch1_img, ch2_img, os.path.join(output_path, file_name)