def test_grid(): """ """ annot = np.zeros((100, 100)) annot[:, 60:] = 2 annot[15:65, 35:85] = 1 np.random.seed(0) noise = annot + np.random.randn(*annot.shape) unary = np.tile(noise[:, :, np.newaxis], [1, 1, 3]) tmp = (unary[:, :, 1] - 1) tmp[annot == 0] *= -1 unary[:, :, 1] = tmp unary[:, :, 2] = 2 - unary[:, :, 2] fig, axarr = plt.subplots(ncols=unary.shape[-1], figsize=(unary.shape[-1] * PLOT_SIZE, PLOT_SIZE)) draw_unary(axarr, unary) fig.tight_layout() fig.savefig(os.path.join(DIR_IMAGES, 'grid_unary.png')) pairwise = (1 - np.eye(3)) * 10 labels = gco.cut_grid_graph_simple(unary, pairwise, n_iter=-1) fig, axarr = plt.subplots(ncols=2, figsize=(2 * PLOT_SIZE, PLOT_SIZE)) axarr[0].set_title('original annotation') axarr[0].imshow(annot, interpolation="nearest") axarr[1].set_title('resulting labeling') axarr[1].imshow(labels.reshape(*annot.shape), interpolation="nearest") axarr[1].contour(annot, colors='w') fig.tight_layout() fig.savefig(os.path.join(DIR_IMAGES, 'grid_labels.png')), plt.close()
def estimate_atlas_graphcut_simple(imgs, ptn_weights, coef=1.): """ run the graphcut to estimate atlas from computed unary terms source: https://github.com/yujiali/pyGCO :param list(ndarray) imgs: list of input binary images [np.array<height, width>] :param ndarray ptn_weights: binary ptn selection np.array<nb_imgs, nb_lbs> :param float coef: coefficient for graphcut :return list(int): >>> atlas = np.zeros((8, 12), dtype=int) >>> atlas[:3, 1:5] = 1 >>> atlas[3:7, 6:12] = 2 >>> luts = np.array([[0, 1, 0]] * 3 + [[0, 0, 1]] * 3 + [[0, 1, 1]] * 3) >>> imgs = [lut[atlas] for lut in luts] >>> estimate_atlas_graphcut_simple(imgs, luts[:, 1:]).astype(int) array([[0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) >>> np.sum(abs(estimate_atlas_graphcut_simple(imgs, luts[:, :1]).astype(int))) 0 """ logging.debug('estimate atlas via GraphCut from Potts model') if ptn_weights.shape[1] <= 1: logging.warning('nothing to do for single label') labels = np.zeros(imgs[0].shape) return labels labeling_sum = compute_positive_cost_images_weights(imgs, ptn_weights) unary_cost = np.array(-1 * labeling_sum, dtype=np.int32) logging.debug('graph unaries potentials %r: \n %r', unary_cost.shape, list(zip(np.histogram(unary_cost, bins=10)))) # original and the right way.. pairwise = (1 - np.eye(labeling_sum.shape[-1])) * coef pairwise_cost = np.array(pairwise, dtype=np.int32) logging.debug('graph pairwise coefs %r', pairwise_cost.shape) # run GraphCut try: labels = cut_grid_graph_simple(unary_cost, pairwise_cost, algorithm='expansion') except Exception: logging.exception('cut_grid_graph_simple') labels = np.argmin(unary_cost, axis=1) # reshape labels labels = labels.reshape(labeling_sum.shape[:2]) logging.debug('resulting labelling %r: \n %r', labels.shape, labels) return labels
def perform_binary_cut(foreground, background): """Perform graph-cut based segmentation. Parameters ---------- foreground, background: float32 Foreground, background probability matrix (w*h*3) """ eps = np.finfo("float").eps foreground_matrix = -np.log(foreground + eps) / np.log(eps) background_matrix = -np.log(background + eps) / np.log(eps) stacked = np.dstack((foreground_matrix, background_matrix)) pairwise = 1 - np.eye(2) print(stacked.shape, pairwise.shape) segmentation = gco.cut_grid_graph_simple(stacked, pairwise, n_iter=-1, algorithm="expansion") return segmentation.reshape(foreground.shape)
def test_binary(): """ """ annot = np.zeros((100, 100)) annot[20:70, 30:80] = 1 np.random.seed(0) img = np.random.randn(*annot.shape) img += 2 * annot - 1 # !!! Be careful when doing this concatenation, # it seems 'c_' does not create a copy # u = np.c_[img.flatten().copy(), - img.flatten().copy()] unary = np.tile(img[:, :, np.newaxis], [1, 1, 2]) unary[:, :, 0] = img unary[:, :, 1] = -img unary += 4 fig, axarr = plt.subplots(ncols=unary.shape[-1], figsize=(unary.shape[-1] * PLOT_SIZE, PLOT_SIZE)) draw_unary(axarr, unary) fig.tight_layout() fig.savefig(os.path.join(DIR_IMAGES, 'binary_unary.png')) # edges, edge_weights = get_uniform_smoothness_pw_single_image(img.shape) smooth = 1 - np.eye(2) # y = pygco.cut_grid_graph_simple(unary, pw_cost*0, n_iter=-1) # labels = pygco.cut_grid_graph_simple(unary_new + np.random. # randn(unary.shape[0], unary.shape[1], unary.shape[2])*0, # pw_cost*0, n_iter=-1) labels = gco.cut_grid_graph_simple(unary, smooth, n_iter=-1) labels_0 = gco.cut_grid_graph_simple(unary, smooth * 0., n_iter=-1) fig, axarr = plt.subplots(ncols=3, figsize=(3 * PLOT_SIZE, PLOT_SIZE)) axarr[0].set_title('image') axarr[0].imshow(img, cmap='gray', interpolation='nearest') axarr[0].contour(annot, colors='r') axarr[1].set_title('labeling (smooth=1)') axarr[1].imshow(labels.reshape(*annot.shape), interpolation='nearest') axarr[1].contour(annot, colors='w') axarr[2].set_title('labeling (smooth=0)') axarr[2].imshow(labels_0.reshape(*annot.shape), interpolation='nearest') axarr[2].contour(annot, colors='w') fig.tight_layout() fig.savefig(os.path.join(DIR_IMAGES, 'binary_labels-4conn.png')), plt.close() labels = gco.cut_grid_graph_simple(unary, smooth, connect=8, n_iter=-1) labels_0 = gco.cut_grid_graph_simple(unary, smooth * 0., connect=8, n_iter=-1) fig, axarr = plt.subplots(ncols=3, figsize=(3 * PLOT_SIZE, PLOT_SIZE)) axarr[0].set_title('image') axarr[0].imshow(img, cmap='gray', interpolation='nearest') axarr[0].contour(annot, colors='r') axarr[1].set_title('labeling (smooth=1)') axarr[1].imshow(labels.reshape(*annot.shape), interpolation='nearest') axarr[1].contour(annot, colors='w') axarr[2].set_title('labeling (smooth=0)') axarr[2].imshow(labels_0.reshape(*annot.shape), interpolation='nearest') axarr[2].contour(annot, colors='w') fig.tight_layout() fig.savefig(os.path.join(DIR_IMAGES, 'binary_labels-8conn.png')), plt.close()