Ejemplo n.º 1
0
 def __test_all_on_image(self, image):
     for bt in self.BOUNDARY_TERMS_2ARGS:
         graph = graph_from_voxels(self.fgmarkers,
                                   self.bgmarkers,
                                   boundary_term=bt,
                                   boundary_term_args=(image, False))
         self.__execute(graph, self.image)
     
     for bt in self.BOUNDARY_TERMS_3ARGS:
         graph = graph_from_voxels(self.fgmarkers,
                                   self.bgmarkers,
                                   boundary_term=bt,
                                   boundary_term_args=(image, 1.0, False))
         self.__execute(graph, self.image)
    def __test_all_on_image(self, image):
        for bt in self.BOUNDARY_TERMS_2ARGS:
            graph = graph_from_voxels(self.fgmarkers,
                                      self.bgmarkers,
                                      boundary_term=bt,
                                      boundary_term_args=(image, False))
            self.__execute(graph, self.image)

        for bt in self.BOUNDARY_TERMS_3ARGS:
            graph = graph_from_voxels(self.fgmarkers,
                                      self.bgmarkers,
                                      boundary_term=bt,
                                      boundary_term_args=(image, 1.0, False))
            self.__execute(graph, self.image)
Ejemplo n.º 3
0
    def test_voxel_based(self):
        """Executes the complete pipeline of the graph cut algorithm."""
        # create the graph from the image
        original_image = scipy.asarray(self.__voriginal_image)
        graph = graph_from_voxels(scipy.asarray(self.__vfg_markers),
                                  scipy.asarray(self.__vbg_markers),
                                  boundary_term=boundary_difference_linear,
                                  boundary_term_args=(original_image, False))

        # execute min-cut / executing BK_MFMC
        try:
            maxflow = graph.maxflow()
        except Exception as e:
            self.fail('An error was thrown during the external executions: {}'.
                      format(e.message))

        # reshape results to form a valid mask
        result = scipy.zeros(original_image.size, dtype=scipy.bool_)
        for idx in range(len(result)):
            result[idx] = 0 if graph.termtype.SINK == graph.what_segment(
                idx) else 1
        result = result.reshape(original_image.shape)

        # check results for validity
        self.assertTrue(
            (result == scipy.asarray(self.__vexpected)).all(),
            'Resulting voxel-based cut is different than expected.')
        self.assertEqual(
            maxflow, self.__vmaxflow,
            'The resulting maxflow {} differs from the expected one {}.'.
            format(maxflow, self.__vmaxflow))
Ejemplo n.º 4
0
 def __test_regional_term_2d(self, term, term_args):
     graph = graph_from_voxels(self.fgmarkers,
                               self.bgmarkers,
                               regional_term=term,
                               regional_term_args=term_args)
     result = self.__execute(graph, self.image)
     assert_array_equal(result, self.result)
 def __test_regional_term_2d(self, term, term_args):
     graph = graph_from_voxels(self.fgmarkers,
                               self.bgmarkers,
                               regional_term=term,
                               regional_term_args=term_args)
     result = self.__execute(graph, self.image)
     assert_array_equal(result, self.result)
Ejemplo n.º 6
0
def graphcut_as_postprocessing(heatmap, image):

    fgmarkers = (heatmap > 0.99).astype(np.float)
    fgmarkers_ = np.zeros(shape=(*fgmarkers.shape, 3))
    for i in range(3):
        fgmarkers_[:, :, i] = fgmarkers

    bgmarkers = (heatmap < 0.01).astype(np.float)
    bgmarkers_ = np.zeros(shape=(*bgmarkers.shape, 3))
    for i in range(3):
        bgmarkers_[:, :, i] = bgmarkers

    image = image.cpu().data.numpy()
    image = np.moveaxis(image, 0, 2)
    image = np.dot(image[..., :3], [0.299, 0.587, 0.114])

    # image = image[:,:,0]

    #
    # image = np.asarray([[0, 0, 0, 0, 0],
    #                        [0, 0, 2, 0, 0],
    #                        [0, 0, 2, 0, 0],
    #                        [0, 0, 2, 0, 0],
    #                        [0, 0, 2, 0, 0]], dtype=np.float)
    # fgmarkers = np.asarray([[0, 0, 0, 0, 0],
    #                            [0, 0, 0, 0, 0],
    #                            [0, 0, 0, 0, 0],
    #                            [0, 0, 0, 0, 0],
    #                            [0, 0, 1, 0, 0]], dtype=np.bool)
    # bgmarkers = np.asarray([[1, 0, 0, 0, 1],
    #                            [0, 0, 0, 0, 0],
    #                            [0, 0, 0, 0, 0],
    #                            [0, 0, 0, 0, 0],
    #                            [0, 0, 0, 0, 0]], dtype=np.bool)
    # expected = image.astype(np.bool)
    graph = graph_from_voxels(fgmarkers,
                              bgmarkers,
                              boundary_term=boundary_difference_exponential,
                              boundary_term_args=(image, 1000, (10, 10)))

    try:
        graph.maxflow()
    except Exception as e:
        print(e)

    # reshape results to form a valid mask
    result = np.zeros(image.size, dtype=np.bool)
    for idx in range(len(result)):
        result[idx] = 0 if graph.termtype.SINK == graph.what_segment(
            idx) else 1
    return (result * 1).reshape(image.shape)
Ejemplo n.º 7
0
def med_graphcut(img, alpha, sigma):
    # to be initialized
    '''
    :alpha: balancing between boundary and regional term.
    :sigma: use in the boundary term. sigma^2 = 1/beta.
    : !spacing: A sequence containing the slice spacing used for weighting
        the computed neighbourhood weight value for different dimensions
    :param img:
    :return:
    '''
    # sigma, alpha = 40. , 1e-2
    spacing = False

    # fg_thresh, bg_thresh = 200, 1  # values between them are Undetermined.

    # set foreground, background seeds
    fg_mark, bg_mark = np.zeros_like(img), np.zeros_like(img)
    img[img < 0] = 0  # ignore negative intensity

    # only for arterial_essence suppression
    max_essence_intensity = 320
    img[img > max_essence_intensity] = max_essence_intensity

    # fg_mark[img>=fg_thresh] = 1
    # bg_mark[img<=bg_thresh] = 1

    # probability map
    # A defect: the histogram should not be the whole image, but the foreground distribution.
    # probability_map = prob_map(img, prob_histogram(img, (bg_thresh+1, 255)))  # bins=256 or others
    # probability_map = np.zeros(img.shape)+1e-4  # only use boundary term
    probability_map = prob_map_md(img)
    # print(probability_map)

    gcgraph = graph_from_voxels(fg_mark,
                                bg_mark,
                                regional_term=regional_probability_map,
                                regional_term_args=(probability_map, alpha),
                                boundary_term=boundary_difference_exponential,
                                boundary_term_args=(img, sigma, spacing))

    maxflow = gcgraph.maxflow()

    result_mask = np.zeros(img.size, dtype=np.bool)
    for idx in range(len(result_mask)):
        result_mask[idx] = 0 if gcgraph.termtype.SINK == gcgraph.what_segment(
            idx) else 1  # ?
    result_mask = result_mask.reshape(img.shape)
    return result_mask, (str(sigma), str(alpha))
 def test_spacing(self):
     image = numpy.asarray(
         [[0, 0, 0, 0, 0], [0, 0, 2, 0, 0], [0, 0, 2, 0, 0],
          [0, 0, 2, 0, 0], [0, 0, 2, 0, 0]],
         dtype=numpy.float)
     fgmarkers = numpy.asarray(
         [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0], [0, 0, 1, 0, 0]],
         dtype=numpy.bool)
     bgmarkers = numpy.asarray(
         [[1, 0, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
         dtype=numpy.bool)
     expected = image.astype(numpy.bool)
     graph = graph_from_voxels(fgmarkers,
                               bgmarkers,
                               boundary_term=boundary_difference_division,
                               boundary_term_args=(image, 1.0, (1., 5.0)))
     result = self.__execute(graph, image)
     assert_array_equal(result, expected)
Ejemplo n.º 9
0
 def test_spacing(self):
     image = numpy.asarray([[0,0,0,0,0],
                            [0,0,2,0,0],
                            [0,0,2,0,0],
                            [0,0,2,0,0],
                            [0,0,2,0,0]], dtype=numpy.float)
     fgmarkers = numpy.asarray([[0,0,0,0,0],
                                [0,0,0,0,0],
                                [0,0,0,0,0],
                                [0,0,0,0,0],
                                [0,0,1,0,0]], dtype=numpy.bool)
     bgmarkers = numpy.asarray([[1,0,0,0,1],
                                [0,0,0,0,0],
                                [0,0,0,0,0],
                                [0,0,0,0,0],
                                [0,0,0,0,0]], dtype=numpy.bool)
     expected = image.astype(numpy.bool)
     graph = graph_from_voxels(fgmarkers,
                               bgmarkers,
                               boundary_term=boundary_difference_division,
                               boundary_term_args=(image, 1.0, (1., 5.0)))
     result = self.__execute(graph, image)
     assert_array_equal(result, expected)
Ejemplo n.º 10
0
def segmentacionGraphCut(imagen,
                         foreground,
                         background,
                         sigma=15.0,
                         spacing=(1.0, 1.0, 1.0)):
    print("Pasamos las imagenes a medpy")
    coche_medpy = skimage_a_medpy(imagen)
    cocheFore_medpy = foreground.transpose()
    cocheBack_medpy = background.transpose()
    print("Creamos el grafo")
    grafo = graph_from_voxels(
        np.array([cocheFore_medpy, cocheFore_medpy,
                  cocheFore_medpy]),  # Marcas de foreground
        np.array([cocheBack_medpy, cocheBack_medpy,
                  cocheBack_medpy]),  # Marcas de backgorund
        boundary_term=boundary_difference_exponential,  #Calculo pesos bordes
        boundary_term_args=(coche_medpy, sigma, spacing))
    print("Calculamos el maxflow")
    grafo.maxflow()
    print("Calculmaos el resultado")
    resultado_medpy = np.zeros(coche_medpy.size, dtype=np.bool)
    for idx in range(len(resultado_medpy)):
        if grafo.termtype.SINK == grafo.what_segment(idx):
            resultado_medpy[idx] = False
        else:
            resultado_medpy[idx] = True
    resultado_medpy = resultado_medpy.reshape(coche_medpy.shape)
    resultado = medpy_a_skimage(resultado_medpy)
    mask = np.zeros([resultado.shape[0], resultado.shape[1]], dtype=bool)
    mask[np.count_nonzero(resultado == True, axis=2) > 1.5] = True
    resultado = medpy_a_skimage(
        np.array([mask.transpose(),
                  mask.transpose(),
                  mask.transpose()]))
    resultado = resultadoMarcado(imagen, resultado * 255)
    io.imshow(resultado)
    return mask, resultado
Ejemplo n.º 11
0
 def test_voxel_based(self):
     """Executes the complete pipeline of the graph cut algorithm."""
     # create the graph from the image
     original_image = scipy.asarray(self.__voriginal_image)
     graph = graph_from_voxels(scipy.asarray(self.__vfg_markers),
                               scipy.asarray(self.__vbg_markers),
                               boundary_term=boundary_difference_linear,
                               boundary_term_args=original_image)
     
     # execute min-cut / executing BK_MFMC
     try:
         maxflow = graph.maxflow()
     except Exception as e:
         self.fail('An error was thrown during the external executions: {}'.format(e.message))
         
     # reshape results to form a valid mask
     result = scipy.zeros(original_image.size, dtype=scipy.bool_)
     for idx in range(len(result)):
         result[idx] = 0 if graph.termtype.SINK == graph.what_segment(idx) else 1
     result = result.reshape(original_image.shape)
         
     # check results for validity
     self.assertTrue((result == scipy.asarray(self.__vexpected)).all(), 'Resulting voxel-based cut is different than expected.')
     self.assertEqual(maxflow, self.__vmaxflow, 'The resulting maxflow {} differs from the expected one {}.'.format(maxflow, self.__vmaxflow))
Ejemplo n.º 12
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
    ['diff_linear', 'diff_exp', 'diff_div', 'diff_pow', 'max_linear', 'max_exp', 'max_div', 'max_pow']
    if 'diff_linear' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_difference_linear
        logger.info('Selected boundary term: linear difference of intensities')
    elif 'diff_exp' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_difference_exponential
        logger.info('Selected boundary term: exponential difference of intensities')
    elif 'diff_div' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_difference_division
        logger.info('Selected boundary term: divided difference of intensities')
    elif 'diff_pow' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_difference_power
        logger.info('Selected boundary term: power based / raised difference of intensities')
    elif 'max_linear' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_maximum_linear
        logger.info('Selected boundary term: linear maximum of intensities')
    elif 'max_exp' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_maximum_exponential
        logger.info('Selected boundary term: exponential maximum of intensities')
    elif 'max_div' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_maximum_division
        logger.info('Selected boundary term: divided maximum of intensities')
    elif 'max_pow' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_maximum_power
        logger.info('Selected boundary term: power based / raised maximum of intensities')

    # load input images
    badditional_image_data, reference_header = 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 == 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.')

    # extract spacing if required
    if args.spacing:
        spacing = header.get_pixel_spacing(reference_header)
        logger.info('Taking spacing of {} into account.'.format(spacing))
    else:
        spacing = False

    # generate graph
    logger.info('Preparing BK_MFMC C++ graph...')
    gcgraph = graphcut.graph_from_voxels(fgmarkers_image_data,
                                         bgmarkers_image_data,
                                         boundary_term = boundary_term,
                                         boundary_term_args = (badditional_image_data, args.sigma, spacing))
    
    # execute min-cut
    logger.info('Executing min-cut...')
    maxflow = gcgraph.maxflow()
    logger.debug('Maxflow is {}'.format(maxflow))
    
    # reshape results to form a valid mask
    logger.info('Applying results...')
    result_image_data = scipy.zeros(bgmarkers_image_data.size, dtype=scipy.bool_)
    for idx in range(len(result_image_data)):
        result_image_data[idx] = 0 if gcgraph.termtype.SINK == gcgraph.what_segment(idx) else 1    
    result_image_data = result_image_data.reshape(bgmarkers_image_data.shape)
    
    # save resulting mask    
    save(result_image_data.astype(scipy.bool_), args.output, reference_header, args.force)

    logger.info('Successfully terminated.')
Ejemplo n.º 13
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
    ['diff_linear', 'diff_exp', 'diff_div', 'diff_pow', 'max_linear', 'max_exp', 'max_div', 'max_pow']
    if 'diff_linear' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_difference_linear
        logger.info('Selected boundary term: linear difference of intensities')
    elif 'diff_exp' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_difference_exponential
        logger.info('Selected boundary term: exponential difference of intensities')
    elif 'diff_div' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_difference_division
        logger.info('Selected boundary term: divided difference of intensities')
    elif 'diff_pow' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_difference_power
        logger.info('Selected boundary term: power based / raised difference of intensities')
    elif 'max_linear' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_maximum_linear
        logger.info('Selected boundary term: linear maximum of intensities')
    elif 'max_exp' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_maximum_exponential
        logger.info('Selected boundary term: exponential maximum of intensities')
    elif 'max_div' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_maximum_division
        logger.info('Selected boundary term: divided maximum of intensities')
    elif 'max_pow' == args.boundary:
        boundary_term = graphcut.energy_voxel.boundary_maximum_power
        logger.info('Selected boundary term: power based / raised maximum of intensities')

    # load input images
    badditional_image_data, reference_header = 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 == 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.')

    # extract spacing if required
    if args.spacing:
        spacing = header.get_pixel_spacing(reference_header)
        logger.info('Taking spacing of {} into account.'.format(spacing))
    else:
        spacing = False

    # generate graph
    logger.info('Preparing BK_MFMC C++ graph...')
    gcgraph = graphcut.graph_from_voxels(fgmarkers_image_data,
                                         bgmarkers_image_data,
                                         boundary_term = boundary_term,
                                         boundary_term_args = (badditional_image_data, args.sigma, spacing))
    
    # execute min-cut
    logger.info('Executing min-cut...')
    maxflow = gcgraph.maxflow()
    logger.debug('Maxflow is {}'.format(maxflow))
    
    # reshape results to form a valid mask
    logger.info('Applying results...')
    result_image_data = scipy.zeros(bgmarkers_image_data.size, dtype=scipy.bool_)
    for idx in range(len(result_image_data)):
        result_image_data[idx] = 0 if gcgraph.termtype.SINK == gcgraph.what_segment(idx) else 1    
    result_image_data = result_image_data.reshape(bgmarkers_image_data.shape)
    
    # save resulting mask    
    save(result_image_data.astype(scipy.bool_), args.output, reference_header, args.force)

    logger.info('Successfully terminated.')