def test_binary(): img = np.random.randn(100, 100) img[25:75, 25:75] += 2 img -= 1 # !!! Be careful when doing this concatenation, it seems 'c_' does not create a copy #u = np.c_[img.flatten().copy(), -img.flatten().copy()] u = np.c_[img.reshape(10000, 1), -img.reshape(10000, 1)].copy() plt.ion() plt.figure() plt.imshow(u[:, 0].reshape(100, 100), cmap='gray', interpolation='nearest') plt.figure() plt.imshow(u[:, 1].reshape(100, 100), cmap='gray', interpolation='nearest') import imgtools.pairwise as pw edges, edge_weights = pw.get_uniform_smoothness_pw_single_image(img.shape) pw_cost = 1 - np.eye(2) # y = pygco.cut_general_graph(edges, edge_weights, u, pw_cost*2, n_iter=-1, algorithm='expansion') unary = np.tile(img[:, :, np.newaxis], [1, 1, 2]) unary[:, :, 0] = img unary[:, :, 1] = -img unary_new = u.reshape((100, 100, 2)) print np.abs(unary - unary_new).max() print(unary != unary_new).any() #import ipdb #ipdb.set_trace() #plt.figure(); plt.imshow(unary[:,:,0], cmap='gray', interpolation='nearest') #plt.figure(); plt.imshow(unary[:,:,1], cmap='gray', interpolation='nearest') #y = pygco.cut_grid_graph_simple(unary, pw_cost*0, n_iter=-1) #y_new = 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) y_new = pygco.cut_grid_graph_simple(unary_new + np.zeros(unary_new.shape), pw_cost * 1, n_iter=-1) y_new2 = pygco.cut_grid_graph_simple(unary_new, pw_cost * 0, n_iter=-1) print unary_new.dtype print(unary_new + np.zeros(unary_new.shape)).dtype #plt.figure(); plt.imshow(y.reshape(100,100), cmap='gray', interpolation='nearest') plt.figure() plt.imshow(y_new.reshape(100, 100), cmap='gray', interpolation='nearest') plt.figure() plt.imshow(y_new2.reshape(100, 100), cmap='gray', interpolation='nearest') t = raw_input('[Press any key]')
def test_grid(): x = np.zeros((100, 100)) x[:,50:] = 2 x[25:75, 25:75] = 1 y = x + np.random.randn(100, 100) unary = np.tile(y[:,:,np.newaxis], [1,1,3]) im = unary[:,:,1] im = im - 1 im[x == 0] *= -1 unary[:,:,1] = im unary[:,:,2] = 2 - unary[:,:,2] plt.ion() plt.figure(); plt.imshow(unary[:,:,0], cmap="gray", interpolation="nearest") plt.figure(); plt.imshow(unary[:,:,1], cmap="gray", interpolation="nearest") plt.figure(); plt.imshow(unary[:,:,2], cmap="gray", interpolation="nearest") pairwise = 1 - np.eye(3) z = pygco.cut_grid_graph_simple(unary, pairwise * 2, n_iter=-1) plt.figure(); plt.imshow(z.reshape(100, 100), cmap="gray", interpolation="nearest") t = raw_input('[Press any key]')
def test_grid(): """ """ annot = np.zeros((100, 100)) annot[:, 50:] = 2 annot[25:75, 25:75] = 1 noise = annot + np.random.randn(100, 100) unary = np.tile(noise[:, :, np.newaxis], [1, 1, 3]) tmp = unary[:, :, 1] tmp = (tmp - 1) tmp[annot == 0] *= -1 unary[:, :, 1] = tmp unary[:, :, 2] = 2 - unary[:, :, 2] fig = plt.figure(figsize=(unary.shape[-1] * 4, 4)) for i in range(unary.shape[-1]): plt.subplot(1, unary.shape[-1], i + 1) plt.imshow(unary[:, :, i], cmap="gray", interpolation="nearest") fig.tight_layout(), fig.savefig('./images/grid_unary.png') pairwise = (1 - np.eye(3)) * 10 labels = pygco.cut_grid_graph_simple(unary, pairwise, n_iter=-1) fig = plt.figure(figsize=(2 * 4, 4)) plt.subplot(1, 2, 1), plt.title('original annotation') plt.imshow(annot, interpolation="nearest") plt.subplot(1, 2, 2), plt.title('resulting labeling') plt.imshow(labels.reshape(100, 100), interpolation="nearest") fig.tight_layout(), fig.savefig('./images/grid_labels.png')
def test_grid(): x = np.zeros((100, 100)) x[:, 50:] = 2 x[25:75, 25:75] = 1 y = x + np.random.randn(100, 100) unary = np.tile(y[:, :, np.newaxis], [1, 1, 3]) im = unary[:, :, 1] im = im - 1 im[x == 0] *= -1 unary[:, :, 1] = im unary[:, :, 2] = 2 - unary[:, :, 2] plt.ion() plt.figure() plt.imshow(unary[:, :, 0], cmap="gray", interpolation="nearest") plt.figure() plt.imshow(unary[:, :, 1], cmap="gray", interpolation="nearest") plt.figure() plt.imshow(unary[:, :, 2], cmap="gray", interpolation="nearest") pairwise = 1 - np.eye(3) z = pygco.cut_grid_graph_simple(unary, pairwise * 2, n_iter=-1) plt.figure() plt.imshow(z.reshape(100, 100), cmap="gray", interpolation="nearest") t = raw_input('[Press any key]')
def test_binary(): img = np.random.randn(100, 100) img[25:75,25:75] += 2 img -= 1 # !!! Be careful when doing this concatenation, it seems 'c_' does not create a copy #u = np.c_[img.flatten().copy(), -img.flatten().copy()] u = np.c_[img.reshape(10000,1), -img.reshape(10000,1)].copy() plt.ion() plt.figure(); plt.imshow(u[:,0].reshape(100,100), cmap='gray', interpolation='nearest') plt.figure(); plt.imshow(u[:,1].reshape(100,100), cmap='gray', interpolation='nearest') import imgtools.pairwise as pw edges, edge_weights = pw.get_uniform_smoothness_pw_single_image(img.shape) pw_cost = 1 - np.eye(2) # y = pygco.cut_general_graph(edges, edge_weights, u, pw_cost*2, n_iter=-1, algorithm='expansion') unary = np.tile(img[:,:,np.newaxis], [1,1,2]) unary[:,:,0] = img unary[:,:,1] = -img unary_new = u.reshape((100,100,2)) print np.abs(unary - unary_new).max() print (unary != unary_new).any() #import ipdb #ipdb.set_trace() #plt.figure(); plt.imshow(unary[:,:,0], cmap='gray', interpolation='nearest') #plt.figure(); plt.imshow(unary[:,:,1], cmap='gray', interpolation='nearest') #y = pygco.cut_grid_graph_simple(unary, pw_cost*0, n_iter=-1) #y_new = 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) y_new = pygco.cut_grid_graph_simple(unary_new + np.zeros(unary_new.shape), pw_cost*1, n_iter=-1) y_new2 = pygco.cut_grid_graph_simple(unary_new, pw_cost*0, n_iter=-1) print unary_new.dtype print (unary_new + np.zeros(unary_new.shape)).dtype #plt.figure(); plt.imshow(y.reshape(100,100), cmap='gray', interpolation='nearest') plt.figure(); plt.imshow(y_new.reshape(100,100), cmap='gray', interpolation='nearest') plt.figure(); plt.imshow(y_new2.reshape(100,100), cmap='gray', interpolation='nearest') t = raw_input('[Press any key]')
def test_binary(): """ """ img = np.random.randn(100, 100) img[25:75, 25:75] += 2 img -= 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.c_[img.reshape(img.size, 1), -img.reshape(img.size, 1)].copy() fig = plt.figure(figsize=(unary.shape[-1] * 4, 4)) for i in range(unary.shape[-1]): plt.subplot(1, unary.shape[-1], i + 1) plt.imshow(unary[:, i].reshape((100, 100)), cmap="gray", interpolation="nearest") fig.tight_layout(), fig.savefig('./images/binary_unary.png') # edges, edge_weights = get_uniform_smoothness_pw_single_image(img.shape) smooth = 1 - np.eye(2) unary = np.tile(img[:,:,np.newaxis], [1, 1, 2]) unary[:, :, 0] = img unary[:, :, 1] = -img unary_new = unary.reshape((100, 100, 2)) assert np.abs(unary - unary_new).max() == 0. assert not (unary != unary_new).any() # 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 = pygco.cut_grid_graph_simple(unary_new + np.zeros(unary_new.shape), smooth, n_iter=-1) labels_0 = pygco.cut_grid_graph_simple(unary_new, smooth * 0, n_iter=-1) fig = plt.figure(figsize=(3 * 4, 4)) plt.subplot(1, 3, 1), plt.title('image') plt.imshow(img, interpolation="nearest") plt.subplot(1, 3, 2), plt.title('labeling (smooth=1)') plt.imshow(labels.reshape(100, 100), interpolation="nearest") plt.subplot(1, 3, 3), plt.title('labeling (smooth=0)') plt.imshow(labels_0.reshape(100, 100), interpolation="nearest") fig.tight_layout(), fig.savefig('./images/binary_labels.png')
def BinaryMixtureCut(Foreground, Background, I=None, Sigma=None): """Performs a binary graph-cut optimization for region masking, given foreground and background probabilities for image and Parameters ---------- I : array_like An intensity image used for calculating the continuity term. If not provided, only the data term from the foreground/background model will drive the graph-cut optimization. Default value = None. Foreground : array_like Intensity image the same size as 'I' with values in the range [0, 1] representing probabilities that each pixel is in the foreground class. Background : array_like Intensity image the same size as 'I' with values in the range [0, 1] representing probabilities that each pixel is in the background class. Sigma : double Parameter controling exponential decay rate of continuity term. Units are intensity values. Recommended ~10% of dynamic range of image. Defaults to 25 if 'I' is type uint8 (range [0, 255]), and 0.1 if type is float (expected range [0, 1]). Default value = None. Notes ----- The graph cutting algorithm is sensitive to the magnitudes of weights in the data variable 'D'. Small probabilities will be magnified by the logarithm in formulating this cost, and so we add a small positive value to each in order to scale them appropriately. Returns ------- Mask : array_like A binary mask indicating the foreground regions. See Also -------- PoissonMixture References ---------- .. [1] Y. Al-Kofahi et al "Improved Automatic Detection and Segmentation of Cell Nuclei in Histopathology Images" in IEEE Transactions on Biomedical Engineering,vol.57,no.4,pp.847-52, 2010. """ # generate a small number for conditioning calculations Small = np.finfo(np.float).eps # formulate unary data costs D = np.stack((-np.log(Background + Small) / -np.log(Small), -np.log(Foreground + Small) / -np.log(Small)), axis=2) # formulate pairwise label costs Pairwise = 1 - np.eye(2) # calculate edge weights between pixels if argument 'I' is provided if I is not None: if Sigma is None: if issubclass(I.dtype.type, np.float): Sigma = 0.1 elif I.dtype.type == np.uint8: Sigma = 25 # formulate vertical and horizontal costs H = np.exp(-(I[:, 0:-1].astype(np.float) - I[:, 1:].astype(np.float))**2 / (2 * Sigma**2)) V = np.exp(-(I[0:-1, :].astype(np.float) - I[1:, :].astype(np.float))**2 / (2 * Sigma**2)) # cut the graph with edge information from image Mask = gc.cut_grid_graph(D, Pairwise, V, H, n_iter=-1, algorithm='expansion') else: # cut the graph without edge information from image Mask = gc.cut_grid_graph_simple(D, Pairwise, n_iter=-1, algorithm='expansion') # reshape solution to image size and return return Mask.reshape(Foreground.shape[0], Foreground.shape[1])