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 tagImage(image):
    '''
    Function that runs ITK connected components on input image
    :param image: nd Array
    :param outputImage: nd Array
    '''

    # Start timing
    tstart = time.process_time()

    # Creatre LogText and start logging
    logText = '\nRunning connected components on : ' + str(
        image.metadata['Name'])

    #Tag image
    output_array = tag_image(image.get_3d_array())

    #Create metadata ditionary and set type to match tagged image
    output_metadata = image.metadata
    image.metadata['Type'] = str(output_array.dtype)

    # Finish timing and add to logText
    tstop = time.process_time()
    logText += '\n\tProcessing finished in ' + str(
        (tstop - tstart)) + ' seconds! '

    return ImageClass(output_array, output_metadata), logText
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):

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

        #Create Image object
        img = ImageClass.from_multidimimage(a3.inputs['Input Image'])
        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)
        print(
            '#########################################################################'
        )
        print(log_text)
        threshold_value = str(log_text.split('\n')[-1].split(':')[-1])

        print(threshold_value)
        print(log_text)
        print(
            '#########################################################################'
        )

        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 read_params(filters=FILTERS):

    out_dict = {}

    #Get Path. If "Output Path" is not set or does not exist use "File Path".
    if os.path.isdir(a3.inputs['Output Path'].path):
        out_dict['Path'] = a3.inputs['Output Path'].path
    else:
        out_dict['Path'] = os.path.dirname(a3.inputs['File Path'].path)

    out_dict['ChA Image'] = ImageClass(a3.inputs['ChA Image'].image,
                                       a3.inputs['ChA Image'].metadata,
                                       a3.inputs['ChA DataBase'])
    out_dict['ChB Image'] = ImageClass(a3.inputs['ChB Image'].image,
                                       a3.inputs['ChB Image'].metadata,
                                       a3.inputs['ChB DataBase'])

    out_dict['to_text'] = a3.inputs['Save to xlsx/text']
    out_dict['remove_filtered'] = a3.inputs['Keep/Remove filtered objects']

    #Load parameters
    settings = {}
    for f in [TRANSLATE[key] for key in FILTERS]:
        settings[value_to_key(TRANSLATE, f)] = {}
        for m in ['min', 'max']:
            settings[value_to_key(TRANSLATE,
                                  f)][m] = a3.inputs['{} {}'.format(f, m)]

    #Generate overlapping settings dictionary
    ovl_settings = {}
    for key in OVLFILTERS:

        if key in settings:

            prefix = key.split(' ', 1)[0]
            filter_key = key.split(' ', 1)[-1]

            if prefix == 'ChA':
                ovl_settings[filter_key + ' in ' + str(
                    a3.inputs['ChA Image'].metadata['Name'])] = settings[key]

            if prefix == 'ChB':
                ovl_settings[filter_key + ' in ' + str(
                    a3.inputs['ChB Image'].metadata['Name'])] = settings[key]

        else:
            ovl_settings[key] = settings[key]

    if a3.inputs['Volume in pixels/um\u00B3'] and ('volume'
                                                   in settings.keys()):

        #Check if unit metadata is available, default Unit is um!!!!!!!!
        unit_list = [
            'PhysicalSizeX', 'PhysicalSizeY', 'PhysicalSizeZ',
            'PhysicalSizeZUnit', 'PhysicalSizeZUnit', 'PhysicalSizeZUnit'
        ]

        missing_unit_A = [
            u for u in unit_list
            if u not in out_dict['ChA Image'].metadata.keys()
        ]
        if len(missing_unit_A) != 0:
            raise Exception('ChA Image is missing the following unit :' +
                            str(missing_unit_A))

        missing_unit_B = [
            u for u in unit_list
            if u not in out_dict['ChB Image'].metadata.keys()
        ]
        if len(missing_unit_B) != 0:
            raise Exception('ChB Image is missing the following unit :' +
                            str(missing_unit_B))

        print('Physical voxel volume is : ' + str(
            float(out_dict['ChA Image'].metadata['PhysicalSizeX']) *
            float(out_dict['ChA Image'].metadata['PhysicalSizeY']) *
            float(out_dict['ChA Image'].metadata['PhysicalSizeZ'])) + ' ' +
              out_dict['ChA Image'].metadata['PhysicalSizeXUnit'] + '*' +
              out_dict['ChA Image'].metadata['PhysicalSizeYUnit'] + '*' +
              out_dict['ChA Image'].metadata['PhysicalSizeZUnit'])

        ovl_settings['volume'] = settings.pop('volume')

    else:
        ovl_settings['voxelCount'] = settings.pop('volume')

    out_dict['Ovl'] = ovl_settings

    #out_dict['FileName']=a3.inputs['FileName']

    return out_dict
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)