def test_out_of_bound_pixel_index(self): """We expect it to fail.""" parents = self.parents.copy() with self.assertRaises(IndexError): mtlib.find_pixel_parent(parents, 42)
def test_wrong_parents_data(self): """The parents image should contains pixel valid indices""" wrong_parents = np.array([0, 3, 2, 10, 49, 50]) # We expect it to fail. with self.assertRaises(IndexError): mtlib.find_pixel_parent(wrong_parents, 3)
def test_negative_pixel_index(self): """We expect it to fail.""" parents = self.parents.copy() # Warning: in numpy you can fetch in both ways. self.assertEqual( mtlib.find_pixel_parent(parents, -3), mtlib.find_pixel_parent(parents, len(parents) - 3)) self.assertEqual( mtlib.find_pixel_parent(parents, -1), mtlib.find_pixel_parent(parents, len(parents) -1))
def test_union_find_canonization(input, R): input_flat = input.flatten() resolution = input_flat.size # Unique value telling if a pixel is defined in the max tree or not. undefined_node = resolution + 2 # We generate an extra vector of pixels that order nodes downard. # This vector allow to traverse the tree both upward and downard # without having to sort childrens of each node. # Initially, we sort pixel by increasing value and add indices in it. sorted_pixels = np.copy(R) # We store in the parent node of each pixel in an image. # To do so we use the index of the pixel (x + y * width). parents = np.full(resolution, fill_value=undefined_node, dtype=np.uint32) # zparents make root finding much faster. zparents = parents.copy() j = resolution - 1 # We go through sorted pixels in the reverse order. for pi in sorted_pixels[::-1]: # Make a node. # By default, a pixel is its own parent. parents[pi] = pi zparents[pi] = pi zp = pi neighbors = max_tree.get_neighbors_2d(4, input.shape, pi, input.size) # Filter neighbors. neighbors = [n for n in neighbors if parents[n] != undefined_node] # Go through neighbors. for nei_pi in neighbors: zn = max_tree.find_pixel_parent(zparents, nei_pi) if zn != zp: if input_flat[zp] == input_flat[zn]: zp, zn = zn, zp # Merge sets. zparents[zn] = zp parents[zn] = zp sorted_pixels[j] = zn j -= 1 max_tree.canonize(input_flat, parents, sorted_pixels) return parents
def test_parents(self): parents = self.parents.copy() self.assertEqual(mtlib.find_pixel_parent(parents, 1), 1) self.assertEqual(mtlib.find_pixel_parent(parents, 3), 1) self.assertEqual(mtlib.find_pixel_parent(parents, 0), 1) self.assertEqual(mtlib.find_pixel_parent(parents, 2), 1) self.assertEqual(mtlib.find_pixel_parent(parents, 4), 1) self.assertEqual(mtlib.find_pixel_parent(parents, 5), 1)