def getans(mode, pshift, drot, iter_num=10, zip=3): from random import uniform, randint names = ["comp1.tif", "comp2.tif", "comp3.tif", "comp4.tif", "comp5.tif"] imgs = [cv2.imread(name) for name in names] TTFF = {"tn": 0, "tp": 0, "fn": 0, "fp": 0} k = 0 dx = dy = imgs[0].shape[0] * pshift for i in range(iter_num): shift1 = (uniform(-dx, dx), uniform(-dy, dy)) rot1 = (randint(-drot, drot)) shift2 = (uniform(-dx, dx), uniform(-dy, dy)) rot2 = (randint(-drot, drot)) if mode == "sim": ind1 = randint(0, 1) ind2 = randint(0, 1) elif mode == "any": ind1 = randint(0, 4) ind2 = randint(0, 4) img1 = tools.get_img(imgs[ind1], shift1, rot1) img2 = tools.get_img(imgs[ind2], shift2, rot2) solver = Solution(img1, img2, zip) #show(segm.extract_bv(img1), name="_____") SIM = solver.estimate() shift1 = [0, 0] rot1, shift1[0], shift1[1] = solver.rotXY print("->", ind1, ind2, "->", SIM) if SIM: #ОДИНАКОВЫЕ if ind1 == ind2: TTFF["tp"] += 1 else: TTFF["fp"] += 1 print("!!!") else: #РАЗНЫЕ if ind1 != ind2: TTFF["tn"] += 1 elif ind1 == ind2: TTFF["fn"] += 1 print("&&") return TTFF
def main(mode="random", iter_num=20, k=5): """average time to 1 pair = (2 / k^2) sec""" if mode == "random": from random import uniform from time import time img1 = cv2.imread("comp1.tif") img1 = tools.resize(img1, k) cont = [] for i in range(iter_num): dx = dy = 0 dr = 0 shift = (uniform(-dx, dx), uniform(-dy, dy)) rot = (uniform(-dr, dr)) img2 = tools.get_img(img1, shift, rot) solver = Solution(img1, img2, 100) print("RIGHT", rot, shift) start = time() solver.estimate() shift1 = [0, 0] rot1, shift1[0], shift1[1] = solver.rotXY if rot1 != False: print("EST", rot1, shift1) print("rotXY", solver.rotXY) delta = [ abs(rot - rot1), abs(shift[0] - shift1[0]), abs(shift[1] - shift1[1]) ] print(f"FALLIBILITY = {delta}") else: print("NOT") cont.append(time() - start) print("___") print( f"MAX = {max(cont)}, MIN = {min(cont)}, AVERAGE = {sum(cont) / iter_num} SECONDS" ) elif mode == "compare": name1, name2 = f"/MESSIDOR/1pp.tif", f"/MESSIDOR/20051216_43913_0200_PP.tif" img1 = (cv2.imread(name1)) img2 = (cv2.imread(name2)) #img2 = tools.rotAlignment(img2, 0) #tools.show(img1) #tools.show(img2) img1 = segm.extract_bv(tools.resize(img1, k)) img2 = segm.extract_bv(tools.resize(img2, k)) solver = Solution(img1, img2) print(solver.estimate()) return 0
def spam(img, key, x, y, k=70): dx = dy = 12 dr = 15 for i in range(k): shift = (uniform(-dx, dx), uniform(-dy, dy)) rot = (uniform(-dr, dr)) imgspam = tools.get_img(img, shift, rot) # tools.show(imgspam) x.append(imgspam) y.append(key)
def test_plot(self): "check that all the plot code runs (not a full proof test but better than nothing)" img = get_img("images/TX1_white_cropped.tif") obj = kmeans_local(img, [4, 4]) obj.iterate(2) fig, ax = plt.subplots() for opt in ['default', 'edges', 'img', 'centers', 'bins']: obj.plot(opt, ax=ax) obj.plot('time') return
def test_iteration(self): "test that clusters still make sense after a single iteration" img = get_img("images/TX1_white_cropped.tif") obj = kmeans_local(img, [4, 4]) obj.update_clusters() obj.update_centroids() assert sum([o.numel() for o in obj.cluster_list]) == obj.Np, \ "clustered vectors needs to be same as number of pixels" assert obj.cluster_tensor.unique().numel() == 16, \ "should be exactly 16 clusters" return
def test_vector_initalisation(self): "test the convergence from 2d rgb image to 5d vectors is correct" set_seed(10) img = get_img("images/TX1_polarised_cropped.tif") obj = kmeans_img(img, 10) assert obj.vectors.numel() == int( img.size * 5 / 3 ), "There should be the same number of elements plus the x and y cordinates" tmp = ((obj.vectors[:, 2] <= 1) * (obj.vectors[:, 2] >= 0) * (obj.vectors[:, 3] <= 1) * (obj.vectors[:, 3] >= 0) * (obj.vectors[:, 4] <= 1) * (obj.vectors[:, 4] >= 0)) assert tmp.all(), "all pixel values must be in the range [0, 1]"
def test_clusters(self): "test clusters are initalised and iterate without any empty clusters" set_seed(10) img = get_img("images/TX1_polarised_cropped.tif") obj = kmeans_img(img, 10) obj.update_clusters() assert all([len(o) for o in obj.clusters.values() ]), "no cluster should be empty intially" obj.update_centroids() obj.update_clusters() assert all([len(o) for o in obj.clusters.values() ]), "no cluster should be after 1 iteration"
def test_bin_setup(self): """ test that the vectors have been binned correctly and clusters initalised correctly """ img = get_img("images/TX1_white_cropped.tif") obj = kmeans_local(img, [4, 4]) # test bins assert sum([o.numel() for o in obj.vec_bins_list]) == obj.Np, \ "binned vectors needs to be same as number of pixels" assert obj.vec_bins_tensor.unique().numel() == 16, \ "should be exactly 16 bins" # test clusters assert sum([o.numel() for o in obj.cluster_list]) == obj.Np, \ "clustered vectors needs to be same as number of pixels" assert obj.cluster_tensor.unique().numel() == 16, \ "should be exactly 16 clusters" return
def test_img_setup(self): "test that the img and vectors are made correctly" set_seed(10) img = get_img("images/TX1_white_cropped.tif") obj = kmeans_local(img, [4, 4]) assert len(obj.adj_bins) == 16, "should be 16 cells" assert len( obj.adj_bins[0] ) == 4, "corner cell should only have 3 neighbours and itself" assert len(obj.adj_bins[1] ) == 6, "edge cell should only have 5 neighbours and itself" assert obj.vectors.numel() == int( img.size * 5 / 3 ), "There should be the same number of elements plus the x and y cordinates" tmp = ((obj.vectors[:, 2] <= 1) * (obj.vectors[:, 2] >= 0) * (obj.vectors[:, 3] <= 1) * (obj.vectors[:, 3] >= 0) * (obj.vectors[:, 4] <= 1) * (obj.vectors[:, 4] >= 0)) assert tmp.all(), "all pixel values must be in the range [0, 1]" return
assert isinstance(mask, type(np.array([]))), \ "mask must be a numpy array" assert mask.ndim == 2, "mask must be a 2d array" # convolve laplacian with mask laplacian = np.array([[1., 1., 1.], [1., -8., 1.], [1., 1., 1.]]) edges = sig.convolve2d(mask, laplacian, mode='valid') return (edges > 0).astype(float) # any non-zero is an edge if __name__ == '__main__': # run an example from tools import get_img # setup image = get_img("images/example_white.tif") obj = SLIC(image, [20, 20]) # plot the initial binning obj.plot("setup") plt.gca().set(title='Initial Grid') # iterate obj.iterate(10) # plot the resulting segmentation obj.plot('default') plt.gca().set(title='Segmentation after 10 Iterations') # plot the time taken obj.plot('time')
elif option == 'seg': mask = self.vector_clusters else: raise (ValueError) # option not recognised # reshape the mask and make it into numpy mask = mask.view(self.y_dim, self.x_dim).cpu().numpy() # if only the edges are wanted use a laplacian convolution if edges: laplacian = np.ones([3, 3]) laplacian[1, 1] = -8 mask = convolve2d(mask, laplacian, mode='valid') mask = (mask > 0).astype(float) # if wanted make into rgba form so that it can overlay in imshow if rgba: zeros = np.zeros_like(mask) mask = np.dstack([mask, zeros, zeros, mask]) return mask #%% if __name__ == '__main__': set_seed(10) img = get_img("images/TX1_polarised_cropped.tif") obj = kmeans_local(img, [4, 4])
for i, filt in enumerate(filts): output[:, :, i] = sig.convolve2d(grey_img, filt, mode='same') output[:, :, i] -= output[:, :, i].mean() output[:, :, i] -= output[:, :, i].std() if verbose: fig, ax = plt.subplots(figsize=[22, 11]) col = ax.imshow(output[:, :, i]) plt.colorbar(col) return output if __name__ == '__main__': # gabor filter example IF_obj = Image_Filters() bank = IF_obj.gabor_bank(13, 5, 20, gamma=1., verbose=True) img = get_img('/content/images/TX1_white_cropped.tif') grey_img = img.mean(axis=2) IF_obj.apply_bank(bank, grey_img, verbose=True) # sobel_edge_detection example IF_obj = Image_Filters() img = get_img('/content/images/TX1_white_cropped.tif') grey_img = img.mean(axis=2) IF_obj.sobel_edge_detection(grey_img, verbose=True)
fig, axs = plt.subplots(2, 1, figsize=[44, 22]) self.plot('polar', ax=axs[0]) self.plot('default', ax=axs[1]) elif option == 'time': assert hasattr(self, 'progress_bar'), 'must call iterate to use this' self.progress_bar.plot_time(ax) ax.set(title='Image Segmentation (time)') # save the figure if wanted if path: plt.savefig(path) # def save_segmentation(self, path): # "Save the segmentation mask for future use" if __name__ == '__main__': # run an example # setup set_seed(10) img = get_img("images/TX1_white_cropped.tif") img_polar = get_img("images/TX1_polarised_cropped.tif") obj_both = kmeans_local(img, [20, 15], polar=img_polar, combo_opt='sum') obj_both.iterate(10) obj_both.plot('both') plt.gca().set(title='Combined after 10 Iterations')
# call the plot routenes for i, _ax in zip(objs, axs): self.SLIC_objs[i].plot(option, ax=_ax) # save the figure if wanted if path: plt.savefig(path) if __name__ == '__main__': # run an example of SLIC on two images, then MSLIC on both from tools import get_img # setup grid = [20, 20] img_white = get_img("images/example_white.tif") img_polar = get_img("images/example_polar.tif") # iterate SLIC with just the white image obj_white = SLIC(img_white, grid) obj_white.iterate(5) obj_white.plot() # iterate SLIC with just the polar image obj_polar = SLIC(img_polar, grid) obj_polar.iterate(5) obj_polar.plot() # iterate MSLIC with both white and polar images obj_both = MSLIC_wrapper([img_white, img_polar], grid) obj_both.iterate(5)
mask = self.vector_cluster_ids.view(self.x_dim, self.y_dim).numpy() if edge: laplacian = np.ones([3, 3]) laplacian[1, 1] = -8 mask = convolve2d(mask, laplacian, mode='full') mask = (mask > 0).astype(float) if rgba: zeros = np.zeros_like(mask) mask = np.dstack([mask, zeros, zeros, mask]) return mask if __name__ == '__main__': from tools import get_img from kmeans_img import kmeans_img set_seed(10) img = get_img("images/TX1_white_cropped.tif") obj = kmeans_img(img, 20, dist_func=dat_distance_metric) obj.iterate(10) mask = obj.get_mask(edge=True, rgba=True) fig, ax = plt.subplots(figsize=[20, 20]) ax.imshow(img) ax.imshow(mask)