def module_main(ctx):

    try:
        a3.outputs['ChA Image'] = a3.inputs['ChA Image']
        a3.outputs['ChB Image'] = a3.inputs['ChB Image']
        a3.outputs['ChA Thresholded'] = ImageClass(
            a3.inputs['ChA Thresholded'].image,
            a3.inputs['ChA Thresholded'].metadata).to_multidimimage()
        a3.outputs['ChB Thresholded'] = ImageClass(
            a3.inputs['ChB Thresholded'].image,
            a3.inputs['ChB Thresholded'].metadata).to_multidimimage()

    except Exception as e:
        error("Error occured while executing '" + str(ctx.type()) +
              "' module '" + str(ctx.name()) + "' !",
              exception=e)
def module_main(ctx):

    try:

        filename = a3.inputs['FileName'].path

        #Inizialization
        tstart = time.clock()
        print(SEPARATOR)
        print('Loading the following image: ', filename)

        #Load and reshape image
        img = ImageClass.load(filename)

        #Print important image parameters
        print_line_by_line(str(img))

        #Create Output 1
        ch_1_Nb = a3.inputs['Channel'] - 1
        ch_1 = img.get_dimension(ch_1_Nb, 'C')
        ch_1.metadata['Path'] = filename
        ch_1.reorder('ZYXCT')
        a3.outputs['Channel'] = ch_1

        #Finalization
        tstop = time.clock()
        print('Processing finished in ' + str((tstop - tstart)) + ' seconds! ')
        print('Image loaded successfully!')
        print(SEPARATOR)

    except Exception as e:
        raise error("Error occured while executing '" + str(ctx.type()) +
                    "' module '" + str(ctx.name()) + "' !",
                    exception=e)
Exemple #3
0
def module_main(ctx):
    
    try:
        #Inizialization
        tstart = time.clock()
        print(SEPARATOR)
        print('Object analysis started!')
        
        #Read Parameters
        print('Reading input parameters!')
        params = read_params()
        
        output=analyze_image(params['Source'],
                   params['Mask'],
                   params['Settings'],
                   params['removeFiltered'])
        
        #Change Name in metadata
        #output.metadata['Name']=params['Mask'].metadata['Name']+'_tagged'

        #Create Output
        a3.outputs['Analyzed Image'] = output
        a3.outputs['Analyzed Binary'] = ImageClass(output.image>0,output.metadata)
        a3.outputs['Analyzed Database']=output.database
      
        #Finalization
        tstop = time.clock()
        print('Processing finished in ' + str((tstop - tstart)) + ' seconds! ')
        print('Object analysis was run successfully!')
        print(SEPARATOR)

    except Exception as e:
        raise error("Error occured while executing '"+str(ctx.type())+"' module '"+str(ctx.name())+"' !",exception=e)
Exemple #4
0
def module_main(ctx):

    print(SEPARATOR)
    print('Retrieving file!')

    #Absolute path
    path = os.path.abspath(a3.inputs['path'].path)

    #Get file extension and directory
    if os.path.isfile(path):

        base_dir = os.path.dirname(path)
        ext = os.path.splitext(path)[1]
        print('Input directory:', base_dir)
    else:
        error(
            "Error occured while executing '" + str(ctx.type()) +
            "' module '" + str(ctx.name()) + "' ! Path is not a file!",
            OSError('Path is not a file!'))

    # Gett all the files with matching extensions
    file_list = [os.path.abspath(x) for x in glob(base_dir + '/*' + ext)]

    if os.path.isfile(path):
        file_list.remove(path)
        file_list.insert(0, path)

    if len(file_list) == 0:
        raise Warning('path {} is empty'.format(base_dir))

    index = ctx.run_id()
    if index < len(file_list) - 1:
        ctx.set_require_next_run(True)
    else:
        ctx.set_require_next_run(False)

    url = a3.Url()
    url.path = file_list[index]

    #Print current filename and index
    _, curr_filename = os.path.split(url.path)
    print('Currently processing:', curr_filename)

    #Set output
    a3.outputs['file'] = url

    print(SEPARATOR)
def module_main(ctx):

    try:
        #Inizialization
        tstart = time.process_time()
        print(SEPARATOR)
        print('Colocalization analysis started!')

        #Read Parameters
        print('Reading input parameters!')
        params = read_params()

        output = colocalize(params['ChA Image'],
                            params['ChB Image'],
                            params['Ovl'],
                            params['Path'],
                            to_text=params['to_text'],
                            remove_filtered=params['remove_filtered'])

        a3.outputs['Overlapping Image'] = output[0]

        a3.outputs['Overlapping Binary'] = ImageClass(output[0].image > 0,
                                                      output[0].metadata)
        a3.outputs['Overlapping DataBase'] = output[0].database

        path = a3.Url()
        path.path = output[3]
        a3.outputs['Overlapping Path'] = path

        #Finalization
        tstop = time.process_time()
        print('Processing finished in ' + str((tstop - tstart)) + ' seconds! ')
        print('Object analysis was run successfully!')
        print(SEPARATOR)
        quote(verbose=True)
        print(SEPARATOR)

    except IOError as e:
        print("Warning: Failed to write to file!!", file=sys.stderr)
        print(str(e), file=sys.stderr)

    except Exception as e:
        error("Error occured while executing '" + str(ctx.type()) +
              "' module '" + str(ctx.name()) + "' !",
              exception=e)
def module_main(ctx):

    try:
        #Inizialization
        tstart = time.clock()
        print(SEPARATOR)
        print('Thresholding started!')

        #Create Image object
        img = ImageClass.from_multidimimage(a3.inputs['Input Image'])
        #img.image=img.image.astype('float')

        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'

        #Run thresholding
        output_img = module_threshold(img, method, kwargs)

        #Set output
        a3.outputs['Thresholded Image'] = output_img
        a3.outputs['Image'] = img

        #Finalization
        tstop = time.clock()
        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)
Exemple #7
0
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 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):

    try:

        filename = a3.inputs['FileName'].path

        #Inizialization
        tstart = time.clock()
        print(SEPARATOR)
        print('Loading the following image: ', filename)

        #Process Files
        directory = os.path.dirname(filename)
        extension = os.path.splitext(filename)[1]

        file_list = [
            f for f in os.listdir(directory)
            if (os.path.isfile(os.path.join(directory, f))
                and os.path.splitext(f)[1] == extension)
        ]

        #Thresholding Methods
        METHODS = [
            'Huang', 'IsoData', 'IsoData_skimage', 'KittlerIllingworth', 'Li',
            'Li_skimage', 'MaxEntropy', 'MaxEntropy_skimage', 'Moments',
            'Otsu', 'Otsu_skimage', 'RenyiEntropy', 'Shanbhag', 'Triangle',
            'Triangle_skimage', 'Yen', 'Yen_skimage'
        ]
        print('Filename ' + 'meanIntensity sumIntensity ' +
              str(METHODS).replace('[', '').replace(']', '').replace(',', ''))
        for name in file_list:

            #Load and reshape image
            img = ImageClass.load(os.path.join(directory, name))

            #Print important image parameters
            #print_line_by_line(str(img))

            ch_1_Nb = a3.inputs['Channel A'] - 1
            ch_1 = img.get_dimension(ch_1_Nb, 'C')
            ch_1.metadata['Path'] = filename
            ch_1.reorder('ZYXCT')

            #Run thresholding
            res = name

            #Analyze raw image parameters
            raw_data = core.analyze_raw(ch_1)

            res += ' ' + str(raw_data['meanIntensity']) + ' ' + str(
                raw_data['sumIntensity'])

            for meth in METHODS:
                ch_1_thr, thr_value = core.threshold(ch_1, meth, mode='Stack')
                res += ' ' + str(thr_value)

            print(res)

        #Output
        a3.outputs['Raw Image'] = ch_1.to_multidimimage()
        a3.outputs['Thresholded Image'] = ch_1_thr.to_multidimimage()

        #Finalization
        tstop = time.clock()
        print('Processing finished in ' + str((tstop - tstart)) + ' seconds! ')
        print('Image loaded successfully!')
        print(SEPARATOR)

    except Exception as e:
        raise error("Error occured while executing '" + str(ctx.type()) +
                    "' module '" + str(ctx.name()) + "' !",
                    exception=e)