Ejemplo n.º 1
0
def main():
    # parse cmd arguments
    parser = getParser()
    parser.parse_args()
    args = getArguments(parser)
    
    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)
        
    # check if output image exists
    if not args.force:
        if os.path.exists(args.output):
            logger.warning('The output image {} already exists. Exiting.'.format(args.output))
            exit(-1)
            
    # select boundary term
    if args.boundary == 'stawiaski':
        boundary_term = graphcut.energy_label.boundary_stawiaski
        logger.info('Selected boundary term: stawiaski')
    else:
        boundary_term = graphcut.energy_label.boundary_difference_of_means
        logger.info('Selected boundary term: difference of means')

    # load input images
    region_image_data, reference_header = load(args.region)
    badditional_image_data, _ = load(args.badditional)
    markers_image_data, _ = load(args.markers)
    
    # split marker image into fg and bg images
    fgmarkers_image_data, bgmarkers_image_data = split_marker(markers_image_data)
       
    # check if all images dimensions are the same
    if not (badditional_image_data.shape == region_image_data.shape == fgmarkers_image_data.shape == bgmarkers_image_data.shape):
        logger.critical('Not all of the supplied images are of the same shape.')
        raise ArgumentError('Not all of the supplied images are of the same shape.')
       
    # recompute the label ids to start from id = 1
    logger.info('Relabel input image...')
    region_image_data = filter.relabel(region_image_data)

    # generate graph
    logger.info('Preparing graph...')
    gcgraph = graphcut.graph_from_labels(region_image_data,
                                    fgmarkers_image_data,
                                    bgmarkers_image_data,
                                    boundary_term = boundary_term,
                                    boundary_term_args = (badditional_image_data)) # second is directedness of graph , 0)

    logger.info('Removing images that are not longer required from memory...')
    del fgmarkers_image_data
    del bgmarkers_image_data
    del badditional_image_data
    
    # execute min-cut
    logger.info('Executing min-cut...')
    maxflow = gcgraph.maxflow()
    logger.debug('Maxflow is {}'.format(maxflow))
    
    # apply results to the region image
    logger.info('Applying results...')
    mapping = [0] # no regions with id 1 exists in mapping, entry used as padding
    mapping.extend(map(lambda x: 0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1,
                       scipy.unique(region_image_data)))
    region_image_data = filter.relabel_map(region_image_data, mapping)
    
    # save resulting mask
    save(region_image_data.astype(scipy.bool_), args.output, reference_header, args.force)

    logger.info('Successfully terminated.')
def main():
    # parse cmd arguments
    parser = getParser()
    parser.parse_args()
    args = getArguments(parser)

    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)

    # check if output image exists
    if not args.force:
        if os.path.exists(args.output):
            logger.warning(
                'The output image {} already exists. Exiting.'.format(
                    args.output))
            exit(-1)

    # load input images
    region_image_data, reference_header = load(args.region)
    markers_image_data, _ = load(args.markers)
    gradient_image_data, _ = load(args.gradient)

    # split marker image into fg and bg images
    logger.info('Extracting foreground and background markers...')
    fgmarkers_image_data, bgmarkers_image_data = split_marker(
        markers_image_data)

    # check if all images dimensions are the same shape
    if not (gradient_image_data.shape == region_image_data.shape ==
            fgmarkers_image_data.shape == bgmarkers_image_data.shape):
        logger.critical(
            'Not all of the supplied images are of the same shape.')
        raise ArgumentError(
            'Not all of the supplied images are of the same shape.')

    # collect cut objects
    cut_xy = __get_bg_bounding_pipe(bgmarkers_image_data)

    # cut volumes
    old_size = region_image_data.shape
    gradient_image_data = gradient_image_data[cut_xy]
    region_image_data = region_image_data[cut_xy]
    fgmarkers_image_data = fgmarkers_image_data[cut_xy]
    bgmarkers_image_data = bgmarkers_image_data[cut_xy]

    # recompute the label ids to start from id = 1
    logger.info('Relabel input image...')
    region_image_data = filter.relabel(region_image_data)

    # generate graph
    logger.info('Preparing graph...')
    gcgraph = graphcut.graph_from_labels(
        region_image_data,
        fgmarkers_image_data,
        bgmarkers_image_data,
        boundary_term=graphcut.energy_label.boundary_stawiaski,
        boundary_term_args=(
            gradient_image_data))  # second is directedness of graph , 0)

    logger.info('Removing images that are not longer required from memory...')
    del fgmarkers_image_data
    del bgmarkers_image_data
    del gradient_image_data

    # execute min-cut
    logger.info('Executing min-cut...')
    maxflow = gcgraph.maxflow()
    logger.debug('Maxflow is {}'.format(maxflow))

    # apply results to the region image
    logger.info('Applying results...')
    mapping = [
        0
    ]  # no regions with id 1 exists in mapping, entry used as padding
    mapping.extend(
        map(
            lambda x: 0 if gcgraph.termtype.SINK == gcgraph.what_segment(
                int(x) - 1) else 1, scipy.unique(region_image_data)))
    region_image_data = filter.relabel_map(region_image_data, mapping)

    # generating final image by increasing the size again
    output_image_data = scipy.zeros(old_size, dtype=scipy.bool_)
    output_image_data[cut_xy] = region_image_data

    # save resulting mask
    save(output_image_data, args.output, reference_header, args.force)

    logger.info('Successfully terminated.')
def main():
    # parse cmd arguments
    parser = getParser()
    parser.parse_args()
    args = getArguments(parser)
    
    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)
        
    # check if output image exists
    if not args.force:
        if os.path.exists(args.output):
            logger.warning('The output image {} already exists. Exiting.'.format(args.output))
            exit(-1)
            
    # select boundary term
    if args.boundary == 'stawiaski':
        boundary_term = graphcut.energy_label.boundary_stawiaski
        logger.info('Selected boundary term: stawiaski')
    else:
        boundary_term = graphcut.energy_label.boundary_difference_of_means
        logger.info('Selected boundary term: difference of means')
        
    # select regional term
    if args.regional == 'atlas':
        regional_term = graphcut.energy_label.regional_atlas
    else:
        regional_term = None

    # load input images
    region_image_data, reference_header = load(args.region)
    markers_image_data, _ = load(args.markers)
    
    # loading and splitting the marker image
    fgmarkers_image_data, bgmarkers_image_data = split_marker(markers_image_data)
    
    badditional_image_data, _ = load(args.badditional)
    
    if 'radditional' in args:
        radditional_image_data, _ = load(args.radditional)
    else:
        radditional_image_data = False
    
       
    # check if all images dimensions are the same
    if not (badditional_image_data.shape == region_image_data.shape == fgmarkers_image_data.shape == bgmarkers_image_data.shape):
        logger.critical('Not all of the supplied images are of the same shape.')
        raise ArgumentError('Not all of the supplied images are of the same shape.')
    if not bool == type(radditional_image_data):
        if not (badditional_image_data.shape == radditional_image_data.shape):
            logger.critical('Not all of the supplied images are of the same shape.')
            raise ArgumentError('Not all of the supplied images are of the same shape.')
       
    # recompute the label ids to start from id = 1
    logger.info('Relabel input image...')
    region_image_data = filter.relabel(region_image_data)

    # generate graph
    logger.info('Preparing graph...')
    gcgraph = graphcut.graph_from_labels(region_image_data,
                                    fgmarkers_image_data,
                                    bgmarkers_image_data,
                                    regional_term = regional_term,
                                    boundary_term = boundary_term,
                                    regional_term_args = (radditional_image_data, args.alpha),
                                    boundary_term_args = (badditional_image_data)) # second (optional) parameter is directedness of graph , 0)

    logger.info('Removing images that are not longer required from memory...')
    del fgmarkers_image_data
    del bgmarkers_image_data
    del radditional_image_data
    del badditional_image_data
    
    # execute min-cut
    logger.info('Executing min-cut...')
    maxflow = gcgraph.maxflow()
    logger.debug('Maxflow is {}'.format(maxflow))
    
    # apply results to the region image
    logger.info('Applying results...')
    mapping = [0] # no regions with id 1 exists in mapping, entry used as padding
    mapping.extend(map(lambda x: 0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1,
                       scipy.unique(region_image_data)))
    region_image_data = filter.relabel_map(region_image_data, mapping)
    
    # save resulting mask
    save(region_image_data.astype(scipy.bool_), args.output, reference_header, args.force)

    logger.info('Successfully terminated.')
Ejemplo n.º 4
0
def main():
    # prepare logger
    logger = Logger.getInstance()
    logger.setLevel(logging.DEBUG)
    
    # input image locations
    #i = '/home/omaier/Experiments/Regionsegmentation/Evaluation_Viscous/00originalvolumes/o09.nii' # original image
    g = '/home/omaier/Experiments/Regionsegmentation/Evaluation_Viscous/01gradient/o09_gradient.nii' # gradient magnitude image
    l = '/home/omaier/Experiments/GraphCut/RegionalTerm/images/label_full.nii' # watershed label image
    fg = '/home/omaier/Experiments/GraphCut/RegionalTerm/images/fg_markers.nii'
    bg = '/home/omaier/Experiments/GraphCut/RegionalTerm/images/bg_markers.nii'
    
    # output image locations
    r = '/home/omaier/Experiments/GraphCut/BoundaryTerm/graphcut_full.nii' # liver mask
    
    # load images
    #i_i = load(i)
    g_i = load(g)
    l_i = load(l)
    fg_i = load(fg)
    bg_i = load(bg) 
    
    # extract and prepare image data
    #i_d = scipy.squeeze(i_i.get_data())
    g_d = scipy.squeeze(g_i.get_data())
    l_d = scipy.squeeze(l_i.get_data())
    fg_d = scipy.squeeze(fg_i.get_data())
    bg_d = scipy.squeeze(bg_i.get_data())
    
    # crop input images to achieve faster execution
    #crop = [slice(50, -100),
    #        slice(50, -100),
    #        slice(50, -100)]
    #g_d = g_d[crop]
    #l_d = l_d[crop]
    #fg_d = fg_d[crop]
    #bg_d = bg_d[crop]       
    
    # recompute the label ids to start from id
    logger.info('Relabel input image...')
    l_d =  filter.relabel(l_d)

    # generate graph
    logger.info('Preparing graph...')
    gr = graphcut.graph_from_labels(l_d, fg_d, bg_d, boundary_term = graphcut.boundary_stawiaski, boundary_term_args = g_d)
    #inconsistent = gr.inconsistent()
    #if inconsistent:
    #    logger.error('The created graph contains inconsistencies: {}'.format('\n'.join(inconsistent)))

    # build graph cut graph from graph
    logger.info('Generating BK_MFMC C++ graph...')
    gcgraph = graphcut.GraphDouble(len(gr.get_nodes()), len(gr.get_nweights()))
    gcgraph.add_node(len(gr.get_nodes()))
    for node, weight in gr.get_tweights().iteritems():
        gcgraph.add_tweights(int(node - 1), weight[0], weight[1])
    for edge, weight in gr.get_nweights().iteritems():
        gcgraph.add_edge(int(edge[0] - 1), int(edge[1] - 1), weight[0], weight[1])    
    
    # execute min-cut
    logger.info('Executing min-cut...')
    maxflow = gcgraph.maxflow()
    logger.debug('Maxflow is {}'.format(maxflow))
    
    # collect
    logger.info('Applying results...')
    l_d = filter.relabel_map(l_d, gcgraph.what_segment, lambda fun, rid: 0 if gcgraph.termtype.SINK == fun(int(rid) - 1) else 1)
                
    logger.info('Saving images resulting mask...')
    # save resulting mask
    l_d = l_d.astype(scipy.bool_)
    save(image_like(l_d, fg_i), r)

    logger.info('Done!')
Ejemplo n.º 5
0
def main():
    # prepare logger
    logger = Logger.getInstance()
    logger.setLevel(logging.DEBUG)

    # input image locations
    #i = '/home/omaier/Experiments/Regionsegmentation/Evaluation_Viscous/00originalvolumes/o09.nii' # original image
    g = '/home/omaier/Experiments/Regionsegmentation/Evaluation_Viscous/01gradient/o09_gradient.nii'  # gradient magnitude image
    l = '/home/omaier/Experiments/GraphCut/RegionalTerm/images/label_full.nii'  # watershed label image
    fg = '/home/omaier/Experiments/GraphCut/RegionalTerm/images/fg_markers.nii'
    bg = '/home/omaier/Experiments/GraphCut/RegionalTerm/images/bg_markers.nii'

    # output image locations
    r = '/home/omaier/Experiments/GraphCut/BoundaryTerm/graphcut_full.nii'  # liver mask

    # load images
    #i_i = load(i)
    g_i = load(g)
    l_i = load(l)
    fg_i = load(fg)
    bg_i = load(bg)

    # extract and prepare image data
    #i_d = scipy.squeeze(i_i.get_data())
    g_d = scipy.squeeze(g_i.get_data())
    l_d = scipy.squeeze(l_i.get_data())
    fg_d = scipy.squeeze(fg_i.get_data())
    bg_d = scipy.squeeze(bg_i.get_data())

    # crop input images to achieve faster execution
    #crop = [slice(50, -100),
    #        slice(50, -100),
    #        slice(50, -100)]
    #g_d = g_d[crop]
    #l_d = l_d[crop]
    #fg_d = fg_d[crop]
    #bg_d = bg_d[crop]

    # recompute the label ids to start from id
    logger.info('Relabel input image...')
    l_d = filter.relabel(l_d)

    # generate graph
    logger.info('Preparing graph...')
    gr = graphcut.graph_from_labels(l_d,
                                    fg_d,
                                    bg_d,
                                    boundary_term=graphcut.boundary_stawiaski,
                                    boundary_term_args=g_d)
    #inconsistent = gr.inconsistent()
    #if inconsistent:
    #    logger.error('The created graph contains inconsistencies: {}'.format('\n'.join(inconsistent)))

    # build graph cut graph from graph
    logger.info('Generating BK_MFMC C++ graph...')
    gcgraph = graphcut.GraphDouble(len(gr.get_nodes()), len(gr.get_nweights()))
    gcgraph.add_node(len(gr.get_nodes()))
    for node, weight in gr.get_tweights().iteritems():
        gcgraph.add_tweights(int(node - 1), weight[0], weight[1])
    for edge, weight in gr.get_nweights().iteritems():
        gcgraph.add_edge(int(edge[0] - 1), int(edge[1] - 1), weight[0],
                         weight[1])

    # execute min-cut
    logger.info('Executing min-cut...')
    maxflow = gcgraph.maxflow()
    logger.debug('Maxflow is {}'.format(maxflow))

    # collect
    logger.info('Applying results...')
    l_d = filter.relabel_map(
        l_d, gcgraph.what_segment, lambda fun, rid: 0
        if gcgraph.termtype.SINK == fun(int(rid) - 1) else 1)

    logger.info('Saving images resulting mask...')
    # save resulting mask
    l_d = l_d.astype(scipy.bool_)
    save(image_like(l_d, fg_i), r)

    logger.info('Done!')
def main():
    # parse cmd arguments
    parser = getParser()
    parser.parse_args()
    args = getArguments(parser)
    
    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)
        
    # check if output image exists
    if not args.force:
        if os.path.exists(args.output):
            logger.warning('The output image {} already exists. Exiting.'.format(args.output))
            exit(-1)

    # load input images
    region_image_data, reference_header = load(args.region)
    markers_image_data, _ = load(args.markers)
    gradient_image_data, _ = load(args.gradient)
    
    # split marker image into fg and bg images
    logger.info('Extracting foreground and background markers...')
    fgmarkers_image_data, bgmarkers_image_data = split_marker(markers_image_data)
       
    # check if all images dimensions are the same shape
    if not (gradient_image_data.shape == region_image_data.shape == fgmarkers_image_data.shape == bgmarkers_image_data.shape):
        logger.critical('Not all of the supplied images are of the same shape.')
        raise ArgumentError('Not all of the supplied images are of the same shape.')
    
    # collect cut objects
    cut_xy = __get_bg_bounding_pipe(bgmarkers_image_data)
    
    # cut volumes
    old_size = region_image_data.shape
    gradient_image_data = gradient_image_data[cut_xy]
    region_image_data = region_image_data[cut_xy]
    fgmarkers_image_data = fgmarkers_image_data[cut_xy]
    bgmarkers_image_data = bgmarkers_image_data[cut_xy]
    
    # recompute the label ids to start from id = 1
    logger.info('Relabel input image...')
    region_image_data = filter.relabel(region_image_data)

    # generate graph
    logger.info('Preparing graph...')
    gcgraph = graphcut.graph_from_labels(region_image_data,
                                    fgmarkers_image_data,
                                    bgmarkers_image_data,
                                    boundary_term = graphcut.energy_label.boundary_stawiaski,
                                    boundary_term_args = (gradient_image_data)) # second is directedness of graph , 0)

    logger.info('Removing images that are not longer required from memory...')
    del fgmarkers_image_data
    del bgmarkers_image_data
    del gradient_image_data
    
    # execute min-cut
    logger.info('Executing min-cut...')
    maxflow = gcgraph.maxflow()
    logger.debug('Maxflow is {}'.format(maxflow))
    
    # apply results to the region image
    logger.info('Applying results...')
    mapping = [0] # no regions with id 1 exists in mapping, entry used as padding
    mapping.extend(map(lambda x: 0 if gcgraph.termtype.SINK == gcgraph.what_segment(int(x) - 1) else 1,
                       scipy.unique(region_image_data)))
    region_image_data = filter.relabel_map(region_image_data, mapping)
    
    # generating final image by increasing the size again
    output_image_data = scipy.zeros(old_size, dtype=scipy.bool_)
    output_image_data[cut_xy] = region_image_data
    
    # save resulting mask
    save(output_image_data, args.output, reference_header, args.force)

    logger.info('Successfully terminated.')