synapse_net.ground_truth.shape_refinement
1import multiprocessing as mp 2from concurrent import futures 3from functools import partial 4from typing import Optional 5 6import numpy as np 7 8import bioimage_cpp as bic 9from scipy.ndimage import binary_erosion 10from skimage import img_as_ubyte 11from skimage.filters import gaussian, rank, sato, sobel 12from skimage.morphology import disk 13from skimage.segmentation import watershed 14 15FILTERS = ("sobel", "laplace", "ggm", "structure-tensor", "sato") 16 17 18def _sato_filter(raw, sigma, max_window=16): 19 if raw.ndim != 2: 20 raise NotImplementedError("The sato filter is only implemented for 2D data.") 21 hmap = sato(raw) 22 hmap = gaussian(hmap, sigma=sigma) 23 hmap -= hmap.min() 24 hmap /= hmap.max() 25 hmap = rank.autolevel(img_as_ubyte(hmap), disk(max_window)).astype("float") / 255 26 return hmap 27 28 29def edge_filter( 30 data: np.ndarray, 31 sigma: float, 32 method: str = "sato", 33 per_slice: bool = True, 34 n_threads: Optional[int] = None, 35) -> np.ndarray: 36 """Find edges in the image data. 37 38 Args: 39 data: The input data. 40 sigma: The smoothing factor applied before the edge filter. 41 method: The method for finding edges. The following methods are supported: 42 - "sobel": Edges are found by smoothing the data and then applying a sobel filter. 43 - "laplace": Edges are found with a laplacian of gaussian filter. 44 - "ggm": Edges are found with a gaussian gradient magnitude filter. 45 - "structure-tensor": Edges are found based on the 1st eigenvalue of the structure tensor. 46 - "sato": Edges are found with a sato-filter, followed by smoothing and leveling. 47 per_slice: Compute the filter per slice instead of for the whole volume. 48 n_threads: Number of threads for parallel computation over the slices. 49 50 Returns: 51 Edge filter response. 52 """ 53 if method not in FILTERS: 54 raise ValueError(f"Invalid edge filter method: {method}. Expect one of {FILTERS}.") 55 56 if per_slice and data.ndim == 3: 57 n_threads = mp.cpu_count() if n_threads is None else n_threads 58 filter_func = partial(edge_filter, sigma=sigma, method=method, per_slice=False) 59 with futures.ThreadPoolExecutor(n_threads) as tp: 60 edge_map = list(tp.map(filter_func, data)) 61 edge_map = np.stack(edge_map) 62 return edge_map 63 64 if method == "sobel": 65 edge_map = gaussian(data, sigma=sigma) 66 edge_map = sobel(edge_map) 67 elif method == "laplace": 68 edge_map = bic.filters.laplacian_of_gaussian(data.astype("float32"), sigma) 69 elif method == "ggm": 70 edge_map = bic.filters.gaussian_gradient_magnitude(data.astype("float32"), sigma) 71 elif method == "structure-tensor": 72 inner_scale, outer_scale = sigma, sigma * 0.5 73 edge_map = bic.filters.structure_tensor_eigenvalues( 74 data.astype("float32"), inner_scale, outer_scale 75 )[..., 0] 76 elif method == "sato": 77 edge_map = _sato_filter(data, sigma) 78 79 return edge_map 80 81 82def refine_vesicle_shapes( 83 vesicles: np.ndarray, 84 edge_map: np.ndarray, 85 foreground_erosion: int = 2, 86 background_erosion: int = 6, 87 fit_to_outer_boundary: bool = False, 88 return_seeds: bool = False, 89 compactness: float = 1.0, 90) -> np.ndarray: 91 """Refine vesicle shapes by fitting vesicles to a boundary map. 92 93 This function erodes the segmented vesicles, and then fits them 94 to a bonudary using a seeded watershed. This is done with two watersheds, 95 one two separate foreground from background and one to separate vesicles within 96 the foreground. 97 98 Args: 99 vesicles: The vesicle segmentation. 100 edge_map: Volume with high intensities for vesicle membrane. 101 You can use `edge_filter` to compute this based on the tomogram. 102 foreground_erosion: By how many pixels the foreground should be eroded in the seeds. 103 background_erosion: By how many pixels the background should be eroded in the seeds. 104 fit_to_outer_boundary: Whether to fit the seeds to the outer membrane by 105 applying a second edge filter to `edge_map`. 106 return_seeds: Whether to return the seeds used for the watershed. 107 compactness: The compactness parameter passed to the watershed function. 108 Higher compactness leads to more regular sized vesicles. 109 110 Returns: 111 The refined vesicles. 112 """ 113 114 fg = vesicles != 0 115 if foreground_erosion > 0: 116 fg_seeds = binary_erosion(fg, iterations=foreground_erosion).astype("uint8") 117 else: 118 fg_seeds = fg.astype("uint8") 119 bg = vesicles == 0 120 bg_seeds = binary_erosion(bg, iterations=background_erosion).astype("uint8") 121 # Create 1 pixel wide mask and set to 1 and add to bg seed 122 # Create a 1-pixel wide boundary at the edges of the tomogram 123 boundary_mask = np.zeros_like(bg, dtype="uint8") 124 125 # Set the boundary to 1 along the edges of each dimension 126 boundary_mask[0, :, :] = 1 127 boundary_mask[-1, :, :] = 1 128 boundary_mask[:, 0, :] = 1 129 boundary_mask[:, -1, :] = 1 130 boundary_mask[:, :, 0] = 1 131 boundary_mask[:, :, -1] = 1 132 133 # Add the boundary to the background seeds without affecting existing seeds 134 bg_seeds = np.clip(bg_seeds + boundary_mask, 0, 1) # Ensure values are either 0 or 1 135 136 if fit_to_outer_boundary: 137 outer_edge_map = edge_filter(edge_map, sigma=2) 138 else: 139 outer_edge_map = edge_map 140 141 seeds = fg_seeds + 2 * bg_seeds 142 refined_mask = watershed(outer_edge_map, seeds, compactness=compactness) 143 refined_mask[refined_mask == 2] = 0 144 145 refined_vesicles = watershed(edge_map, vesicles, mask=refined_mask, compactness=compactness) 146 147 if return_seeds: 148 return refined_vesicles, seeds 149 return refined_vesicles
FILTERS =
('sobel', 'laplace', 'ggm', 'structure-tensor', 'sato')
def
edge_filter( data: numpy.ndarray, sigma: float, method: str = 'sato', per_slice: bool = True, n_threads: Optional[int] = None) -> numpy.ndarray:
30def edge_filter( 31 data: np.ndarray, 32 sigma: float, 33 method: str = "sato", 34 per_slice: bool = True, 35 n_threads: Optional[int] = None, 36) -> np.ndarray: 37 """Find edges in the image data. 38 39 Args: 40 data: The input data. 41 sigma: The smoothing factor applied before the edge filter. 42 method: The method for finding edges. The following methods are supported: 43 - "sobel": Edges are found by smoothing the data and then applying a sobel filter. 44 - "laplace": Edges are found with a laplacian of gaussian filter. 45 - "ggm": Edges are found with a gaussian gradient magnitude filter. 46 - "structure-tensor": Edges are found based on the 1st eigenvalue of the structure tensor. 47 - "sato": Edges are found with a sato-filter, followed by smoothing and leveling. 48 per_slice: Compute the filter per slice instead of for the whole volume. 49 n_threads: Number of threads for parallel computation over the slices. 50 51 Returns: 52 Edge filter response. 53 """ 54 if method not in FILTERS: 55 raise ValueError(f"Invalid edge filter method: {method}. Expect one of {FILTERS}.") 56 57 if per_slice and data.ndim == 3: 58 n_threads = mp.cpu_count() if n_threads is None else n_threads 59 filter_func = partial(edge_filter, sigma=sigma, method=method, per_slice=False) 60 with futures.ThreadPoolExecutor(n_threads) as tp: 61 edge_map = list(tp.map(filter_func, data)) 62 edge_map = np.stack(edge_map) 63 return edge_map 64 65 if method == "sobel": 66 edge_map = gaussian(data, sigma=sigma) 67 edge_map = sobel(edge_map) 68 elif method == "laplace": 69 edge_map = bic.filters.laplacian_of_gaussian(data.astype("float32"), sigma) 70 elif method == "ggm": 71 edge_map = bic.filters.gaussian_gradient_magnitude(data.astype("float32"), sigma) 72 elif method == "structure-tensor": 73 inner_scale, outer_scale = sigma, sigma * 0.5 74 edge_map = bic.filters.structure_tensor_eigenvalues( 75 data.astype("float32"), inner_scale, outer_scale 76 )[..., 0] 77 elif method == "sato": 78 edge_map = _sato_filter(data, sigma) 79 80 return edge_map
Find edges in the image data.
Arguments:
- data: The input data.
- sigma: The smoothing factor applied before the edge filter.
- method: The method for finding edges. The following methods are supported:
- "sobel": Edges are found by smoothing the data and then applying a sobel filter.
- "laplace": Edges are found with a laplacian of gaussian filter.
- "ggm": Edges are found with a gaussian gradient magnitude filter.
- "structure-tensor": Edges are found based on the 1st eigenvalue of the structure tensor.
- "sato": Edges are found with a sato-filter, followed by smoothing and leveling.
- per_slice: Compute the filter per slice instead of for the whole volume.
- n_threads: Number of threads for parallel computation over the slices.
Returns:
Edge filter response.
def
refine_vesicle_shapes( vesicles: numpy.ndarray, edge_map: numpy.ndarray, foreground_erosion: int = 2, background_erosion: int = 6, fit_to_outer_boundary: bool = False, return_seeds: bool = False, compactness: float = 1.0) -> numpy.ndarray:
83def refine_vesicle_shapes( 84 vesicles: np.ndarray, 85 edge_map: np.ndarray, 86 foreground_erosion: int = 2, 87 background_erosion: int = 6, 88 fit_to_outer_boundary: bool = False, 89 return_seeds: bool = False, 90 compactness: float = 1.0, 91) -> np.ndarray: 92 """Refine vesicle shapes by fitting vesicles to a boundary map. 93 94 This function erodes the segmented vesicles, and then fits them 95 to a bonudary using a seeded watershed. This is done with two watersheds, 96 one two separate foreground from background and one to separate vesicles within 97 the foreground. 98 99 Args: 100 vesicles: The vesicle segmentation. 101 edge_map: Volume with high intensities for vesicle membrane. 102 You can use `edge_filter` to compute this based on the tomogram. 103 foreground_erosion: By how many pixels the foreground should be eroded in the seeds. 104 background_erosion: By how many pixels the background should be eroded in the seeds. 105 fit_to_outer_boundary: Whether to fit the seeds to the outer membrane by 106 applying a second edge filter to `edge_map`. 107 return_seeds: Whether to return the seeds used for the watershed. 108 compactness: The compactness parameter passed to the watershed function. 109 Higher compactness leads to more regular sized vesicles. 110 111 Returns: 112 The refined vesicles. 113 """ 114 115 fg = vesicles != 0 116 if foreground_erosion > 0: 117 fg_seeds = binary_erosion(fg, iterations=foreground_erosion).astype("uint8") 118 else: 119 fg_seeds = fg.astype("uint8") 120 bg = vesicles == 0 121 bg_seeds = binary_erosion(bg, iterations=background_erosion).astype("uint8") 122 # Create 1 pixel wide mask and set to 1 and add to bg seed 123 # Create a 1-pixel wide boundary at the edges of the tomogram 124 boundary_mask = np.zeros_like(bg, dtype="uint8") 125 126 # Set the boundary to 1 along the edges of each dimension 127 boundary_mask[0, :, :] = 1 128 boundary_mask[-1, :, :] = 1 129 boundary_mask[:, 0, :] = 1 130 boundary_mask[:, -1, :] = 1 131 boundary_mask[:, :, 0] = 1 132 boundary_mask[:, :, -1] = 1 133 134 # Add the boundary to the background seeds without affecting existing seeds 135 bg_seeds = np.clip(bg_seeds + boundary_mask, 0, 1) # Ensure values are either 0 or 1 136 137 if fit_to_outer_boundary: 138 outer_edge_map = edge_filter(edge_map, sigma=2) 139 else: 140 outer_edge_map = edge_map 141 142 seeds = fg_seeds + 2 * bg_seeds 143 refined_mask = watershed(outer_edge_map, seeds, compactness=compactness) 144 refined_mask[refined_mask == 2] = 0 145 146 refined_vesicles = watershed(edge_map, vesicles, mask=refined_mask, compactness=compactness) 147 148 if return_seeds: 149 return refined_vesicles, seeds 150 return refined_vesicles
Refine vesicle shapes by fitting vesicles to a boundary map.
This function erodes the segmented vesicles, and then fits them to a bonudary using a seeded watershed. This is done with two watersheds, one two separate foreground from background and one to separate vesicles within the foreground.
Arguments:
- vesicles: The vesicle segmentation.
- edge_map: Volume with high intensities for vesicle membrane.
You can use
edge_filterto compute this based on the tomogram. - foreground_erosion: By how many pixels the foreground should be eroded in the seeds.
- background_erosion: By how many pixels the background should be eroded in the seeds.
- fit_to_outer_boundary: Whether to fit the seeds to the outer membrane by
applying a second edge filter to
edge_map. - return_seeds: Whether to return the seeds used for the watershed.
- compactness: The compactness parameter passed to the watershed function. Higher compactness leads to more regular sized vesicles.
Returns:
The refined vesicles.