Beispiel #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 file exists
    if not args.force:
        if os.path.exists(args.image):
            logger.warning('The output file {} already exists. Exiting.'.format(args.image))
            sys.exit(0)
    
    logger.info('Unpickle testbench and loading label image...')
    label, label_img, bounding_boxes, model_fg_ids, model_bg_ids, truth_fg, truth_bg = __load(args.testbench, args.label)
    
    logger.info('Composing image image...')
    image = scipy.zeros(label.shape, dtype=scipy.int8)
    # set foreground ids
    for rid in truth_fg:
        image[bounding_boxes[rid - 1]][label[bounding_boxes[rid - 1]] == rid] = 1
    # set background ids
    for rid in truth_bg:
        image[bounding_boxes[rid - 1]][label[bounding_boxes[rid - 1]] == rid] = 2
    # set foreground model ids
    for rid in model_fg_ids:
        image[bounding_boxes[rid - 1]][label[bounding_boxes[rid - 1]] == rid] = 3
    # set background model ids
    for rid in model_bg_ids:
        image[bounding_boxes[rid - 1]][label[bounding_boxes[rid - 1]] == rid] = 4
    
    logger.info('Saving image as {} with data-type int8...'.format(args.image))
    image_img = image_like(image, label_img)
    image_img.get_header().set_data_dtype(scipy.int8)
    save(image_img, args.image)
    
    logger.info('Successfully terminated.')
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
    #i = '/home/omaier/Temp/test.nii' # original image
    #i = '/home/omaier/Temp/o09_smoothed_i4.0_c0.1_t0.0625.nii'
    i = '/home/omaier/Experiments/GraphCut/BoundaryTerm/Stawiaski/01gradient/o09_gradient.nii'
    
    # output image locations
    r = '/home/omaier/Temp/result_gradient.nii' # result mask
    
    # load images
    i_i = load(i)
 
    # extract and prepare image data
    i_d = scipy.squeeze(i_i.get_data())
    
    # crop input images to achieve faster execution
    crop = [slice(50, -200),
            slice(50, -150),
            slice(50, -100)]
    #i_d = i_d[crop]   
    
    i_d = scipy.copy(i_d)
    
    # !TODO: Test if input image is of size 0
    
    logger.debug('input image shape={},ndims={},dtype={}'.format(i_d.shape, i_d.ndim, i_d.dtype))

    result = watershed8(i_d, logger)

    logger.info('Saving resulting region map...')
    result_i = image_like(result, i_i)
    result_i.get_header().set_data_dtype(scipy.int32)
    save(result_i, r)

    logger.info('Done!')
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
    #i = '/home/omaier/Temp/test.nii' # original image
    #i = '/home/omaier/Temp/o09_smoothed_i4.0_c0.1_t0.0625.nii'
    i = '/home/omaier/Experiments/GraphCut/BoundaryTerm/Stawiaski/01gradient/o09_gradient.nii'

    # output image locations
    r = '/home/omaier/Temp/result_gradient.nii'  # result mask

    # load images
    i_i = load(i)

    # extract and prepare image data
    i_d = scipy.squeeze(i_i.get_data())

    # crop input images to achieve faster execution
    crop = [slice(50, -200), slice(50, -150), slice(50, -100)]
    #i_d = i_d[crop]

    i_d = scipy.copy(i_d)

    # !TODO: Test if input image is of size 0

    logger.debug('input image shape={},ndims={},dtype={}'.format(
        i_d.shape, i_d.ndim, i_d.dtype))

    result = watershed8(i_d, logger)

    logger.info('Saving resulting region map...')
    result_i = image_like(result, i_i)
    result_i.get_header().set_data_dtype(scipy.int32)
    save(result_i, r)

    logger.info('Done!')
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!')
Beispiel #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)

    # build output image name
    output_hdr_name = args.output + '.hdr'
    output_img_name = args.output + '.img'
    output_msk_name = args.output + '.msk'

    # check if output image exists
    if not args.force:
        if os.path.exists(output_hdr_name):
            logger.warning(
                'The output header {} already exists. Breaking.'.format(
                    output_hdr_name))
            exit(1)
        elif os.path.exists(output_img_name):
            logger.warning(
                'The output image {} already exists. Breaking.'.format(
                    output_img_name))
            exit(1)
        elif os.path.exists(output_msk_name):
            logger.warning(
                'The output infor file {} already exists. Breaking.'.format(
                    output_msk_name))
            exit(1)

    # decide on most suitable bit format
    if len(args.masks) / 2 <= 8:
        bit_format = scipy.uint8
    elif len(args.masks) / 2 <= 16:
        bit_format = scipy.uint16
    elif len(args.masks) / 2 <= 32:
        bit_format = scipy.uint32
    elif len(args.masks) / 2 <= 64:
        bit_format = scipy.uint64
    else:
        raise ArgumentError(
            'It is not possible to combine more than 64 single masks.')

    logger.info(
        'Creating a Radiance® segmentation image in {} bit format...'.format(
            bit_format))

    # loading first mask image as reference and template for saving
    logger.info('Loading mask {} ({} segmentation) using NiBabel...'.format(
        args.masks[0], args.masks[1]))
    image_mask = load(args.masks[0])
    image_mask_data = scipy.squeeze(image_mask.get_data())

    # prepare result image
    image_radiance_data = scipy.zeros(image_mask_data.shape, dtype=bit_format)

    logger.debug('Result image is of dimensions {} and type {}.'.format(
        image_radiance_data.shape, image_radiance_data.dtype))

    # preparing .msk file
    f = open(output_msk_name, 'w')

    # adding first mask to result image
    image_radiance_data[image_mask_data > 0] = 1

    # adding first mask segmentation identifier to the .msk file
    f.write('{}\t1\t{}\t{}\t{}\n'.format(args.masks[1],
                                         *__COLOURS[0 % len(__COLOURS)]))

    for i in range(2, len(args.masks), 2):
        # loading mask image
        logger.info(
            'Loading mask {} ({} segmentation) using NiBabel...'.format(
                args.masks[i], args.masks[i + 1]))
        image_mask_data = scipy.squeeze(load(args.masks[i]).get_data())

        # check if the shape of the images is consistent
        if image_mask_data.shape != image_radiance_data.shape:
            raise ArgumentError(
                'Mask {} is with {} of a different shape as the first mask image (which has {}).'
                .format(args.masks[i], image_mask_data.shape,
                        image_radiance_data.shape))

        # adding mask to result image
        image_radiance_data[image_mask_data > 0] += pow(2, i / 2)

        # adding mask segmentation identifier to the .msk file
        f.write('{}\t{}\t{}\t{}\t{}\n'.format(
            args.masks[i + 1], pow(2, i / 2),
            *__COLOURS[(i / 2) % len(__COLOURS)]))

    logger.info(
        'Saving Radiance® segmentation image as {}/.img/.msk...'.format(
            output_hdr_name))
    image_mask.get_header().set_data_dtype(bit_format)
    save(image_like(image_radiance_data, image_mask), output_hdr_name)

    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)
    
    # build output image name
    output_hdr_name = args.output + '.hdr'
    output_img_name = args.output + '.img'
    output_msk_name = args.output + '.msk'
    
    # check if output image exists
    if not args.force:
        if os.path.exists(output_hdr_name):
            logger.warning('The output header {} already exists. Breaking.'.format(output_hdr_name))
            exit(1)
        elif os.path.exists(output_img_name):
            logger.warning('The output image {} already exists. Breaking.'.format(output_img_name))
            exit(1)
        elif os.path.exists(output_msk_name):
            logger.warning('The output infor file {} already exists. Breaking.'.format(output_msk_name))
            exit(1)
    
    # decide on most suitable bit format        
    if len(args.masks) / 2 <= 8:
        bit_format = scipy.uint8
    elif len(args.masks) / 2 <= 16:
        bit_format = scipy.uint16
    elif len(args.masks) / 2 <= 32:
        bit_format = scipy.uint32
    elif len(args.masks) / 2 <= 64:
        bit_format = scipy.uint64
    else:
        raise ArgumentError('It is not possible to combine more than 64 single masks.')
    
    logger.info('Creating a Radiance® segmentation image in {} bit format...'.format(bit_format))
    
    # loading first mask image as reference and template for saving
    logger.info('Loading mask {} ({} segmentation) using NiBabel...'.format(args.masks[0], args.masks[1]))
    image_mask = load(args.masks[0])
    image_mask_data = scipy.squeeze(image_mask.get_data())
    
    # prepare result image
    image_radiance_data = scipy.zeros(image_mask_data.shape, dtype=bit_format)
    
    logger.debug('Result image is of dimensions {} and type {}.'.format(image_radiance_data.shape, image_radiance_data.dtype))
    
    # preparing .msk file
    f = open(output_msk_name, 'w')
    
    # adding first mask to result image
    image_radiance_data[image_mask_data > 0] = 1
    
    # adding first mask segmentation identifier to the .msk file
    f.write('{}\t1\t{}\t{}\t{}\n'.format(args.masks[1], *__COLOURS[0%len(__COLOURS)]))
            
    for i in range(2, len(args.masks), 2):
        # loading mask image
        logger.info('Loading mask {} ({} segmentation) using NiBabel...'.format(args.masks[i], args.masks[i+1]))
        image_mask_data = scipy.squeeze(load(args.masks[i]).get_data())
        
        # check if the shape of the images is consistent
        if image_mask_data.shape != image_radiance_data.shape:
            raise ArgumentError('Mask {} is with {} of a different shape as the first mask image (which has {}).'.format(args.masks[i], image_mask_data.shape, image_radiance_data.shape))
        
        # adding mask to result image
        image_radiance_data[image_mask_data > 0] += pow(2, i/2)
        
        # adding mask segmentation identifier to the .msk file
        f.write('{}\t{}\t{}\t{}\t{}\n'.format(args.masks[i+1], pow(2, i/2), *__COLOURS[(i/2)%len(__COLOURS)]))

    logger.info('Saving Radiance® segmentation image as {}/.img/.msk...'.format(output_hdr_name))
    image_mask.get_header().set_data_dtype(bit_format)
    save(image_like(image_radiance_data, image_mask), output_hdr_name)
    
    logger.info('Successfully terminated.')