|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import argparse |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +import napari |
| 7 | +import numpy as np |
| 8 | +from elf.io import open_file |
| 9 | +from elf.segmentation.utils import load_mutex_watershed_problem |
| 10 | +from skimage.feature import peak_local_max |
| 11 | +from skimage.measure import label as label_components |
| 12 | +from skimage.segmentation import find_boundaries, watershed |
| 13 | + |
| 14 | +import bioimage_cpp as bic |
| 15 | + |
| 16 | + |
| 17 | +THIS_DIR = Path(__file__).resolve().parent |
| 18 | +DEFAULT_DATA_PREFIX = THIS_DIR / "isbi-data-" |
| 19 | + |
| 20 | + |
| 21 | +def load_problem(data_prefix: Path, ndim: int, z_slice: int): |
| 22 | + affinities, offsets = load_mutex_watershed_problem(prefix=str(data_prefix)) |
| 23 | + offsets = [tuple(int(v) for v in offset) for offset in offsets] |
| 24 | + if ndim == 2: |
| 25 | + channels_2d = [index for index, offset in enumerate(offsets) if offset[0] == 0] |
| 26 | + affinities = affinities[channels_2d, z_slice] |
| 27 | + offsets = [offsets[index][1:] for index in channels_2d] |
| 28 | + elif ndim != 3: |
| 29 | + raise ValueError(f"ndim must be 2 or 3, got {ndim}") |
| 30 | + |
| 31 | + direct_channels = [ |
| 32 | + index for index, offset in enumerate(offsets) if sum(abs(v) for v in offset) == 1 |
| 33 | + ] |
| 34 | + direct_affinities = np.ascontiguousarray(affinities[direct_channels], dtype=np.float32) |
| 35 | + direct_offsets = [offsets[index] for index in direct_channels] |
| 36 | + return direct_affinities, direct_offsets |
| 37 | + |
| 38 | + |
| 39 | +def load_raw(data_prefix: Path, ndim: int, z_slice: int): |
| 40 | + data_path = data_prefix.with_name(data_prefix.name + "test.h5") |
| 41 | + with open_file(data_path, "r") as f: |
| 42 | + raw = f["raw"][z_slice] if ndim == 2 else f["raw"][:] |
| 43 | + return raw |
| 44 | + |
| 45 | + |
| 46 | +def make_heightmap(affinities: np.ndarray) -> np.ndarray: |
| 47 | + return np.ascontiguousarray(np.mean(affinities, axis=0), dtype=np.float32) |
| 48 | + |
| 49 | + |
| 50 | +def make_watershed_oversegmentation( |
| 51 | + heightmap: np.ndarray, |
| 52 | + *, |
| 53 | + min_distance: int, |
| 54 | + grid_spacing: int, |
| 55 | + max_markers: int, |
| 56 | +) -> np.ndarray: |
| 57 | + coordinates = peak_local_max( |
| 58 | + -heightmap, |
| 59 | + min_distance=min_distance, |
| 60 | + exclude_border=False, |
| 61 | + num_peaks=max_markers, |
| 62 | + ) |
| 63 | + marker_mask = np.zeros(heightmap.shape, dtype=bool) |
| 64 | + if len(coordinates) > 0: |
| 65 | + marker_mask[tuple(coordinates.T)] = True |
| 66 | + markers = label_components(marker_mask).astype(np.int32, copy=False) |
| 67 | + |
| 68 | + if int(markers.max()) < 2: |
| 69 | + markers = np.zeros(heightmap.shape, dtype=np.int32) |
| 70 | + slices = tuple(slice(None, None, grid_spacing) for _ in heightmap.shape) |
| 71 | + marker_coordinates = np.argwhere(np.ones(heightmap.shape, dtype=bool)[slices]) |
| 72 | + marker_coordinates *= grid_spacing |
| 73 | + for marker_id, coord in enumerate(marker_coordinates, start=1): |
| 74 | + markers[tuple(coord)] = marker_id |
| 75 | + |
| 76 | + return watershed(heightmap, markers=markers).astype(np.uint32, copy=False) |
| 77 | + |
| 78 | + |
| 79 | +def multicut_from_affinities( |
| 80 | + affinities: np.ndarray, |
| 81 | + offsets: list[tuple[int, ...]], |
| 82 | + *, |
| 83 | + threshold: float, |
| 84 | + number_of_threads: int, |
| 85 | + watershed_min_distance: int, |
| 86 | + watershed_grid_spacing: int, |
| 87 | + max_markers: int, |
| 88 | +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: |
| 89 | + heightmap = make_heightmap(affinities) |
| 90 | + oversegmentation = make_watershed_oversegmentation( |
| 91 | + heightmap, |
| 92 | + min_distance=watershed_min_distance, |
| 93 | + grid_spacing=watershed_grid_spacing, |
| 94 | + max_markers=max_markers, |
| 95 | + ) |
| 96 | + |
| 97 | + rag = bic.graph.region_adjacency_graph( |
| 98 | + oversegmentation, number_of_threads=number_of_threads |
| 99 | + ) |
| 100 | + features = bic.graph.affinity_features( |
| 101 | + rag, |
| 102 | + oversegmentation, |
| 103 | + affinities, |
| 104 | + offsets, |
| 105 | + number_of_threads=number_of_threads, |
| 106 | + ) |
| 107 | + edge_costs = threshold - features[:, 0] |
| 108 | + |
| 109 | + objective = bic.graph.MulticutObjective(rag, edge_costs) |
| 110 | + node_labels = bic.graph.ChainedMulticutSolvers( |
| 111 | + [ |
| 112 | + bic.graph.GreedyAdditiveMulticut(), |
| 113 | + bic.graph.KernighanLinMulticut(number_of_outer_iterations=10), |
| 114 | + ] |
| 115 | + ).optimize(objective) |
| 116 | + segmentation = bic.graph.project_node_labels_to_pixels( |
| 117 | + rag, |
| 118 | + oversegmentation, |
| 119 | + node_labels, |
| 120 | + number_of_threads=number_of_threads, |
| 121 | + ) |
| 122 | + return heightmap, oversegmentation, segmentation |
| 123 | + |
| 124 | + |
| 125 | +def main(): |
| 126 | + parser = argparse.ArgumentParser( |
| 127 | + description="Run watershed oversegmentation + RAG multicut on the ISBI affinity example." |
| 128 | + ) |
| 129 | + parser.add_argument("--ndim", type=int, choices=(2, 3), default=2) |
| 130 | + parser.add_argument("--z-slice", type=int, default=0) |
| 131 | + parser.add_argument("--data-prefix", type=Path, default=DEFAULT_DATA_PREFIX) |
| 132 | + parser.add_argument("--threshold", type=float, default=0.1) |
| 133 | + parser.add_argument("--threads", type=int, default=0) |
| 134 | + parser.add_argument("--watershed-min-distance", type=int, default=5) |
| 135 | + parser.add_argument("--watershed-grid-spacing", type=int, default=12) |
| 136 | + parser.add_argument("--max-markers", type=int, default=2048) |
| 137 | + args = parser.parse_args() |
| 138 | + |
| 139 | + affinities, offsets = load_problem(args.data_prefix, args.ndim, args.z_slice) |
| 140 | + raw = load_raw(args.data_prefix, args.ndim, args.z_slice) |
| 141 | + heightmap, oversegmentation, segmentation = multicut_from_affinities( |
| 142 | + affinities, |
| 143 | + offsets, |
| 144 | + threshold=args.threshold, |
| 145 | + number_of_threads=args.threads, |
| 146 | + watershed_min_distance=args.watershed_min_distance, |
| 147 | + watershed_grid_spacing=args.watershed_grid_spacing, |
| 148 | + max_markers=args.max_markers, |
| 149 | + ) |
| 150 | + |
| 151 | + viewer = napari.Viewer() |
| 152 | + viewer.add_image(raw, name="raw") |
| 153 | + viewer.add_image(affinities, name="direct affinities") |
| 154 | + viewer.add_image(heightmap, name="watershed heightmap") |
| 155 | + viewer.add_labels(oversegmentation, name="watershed oversegmentation") |
| 156 | + viewer.add_labels(segmentation, name="multicut segmentation") |
| 157 | + viewer.add_labels(find_boundaries(segmentation), name="multicut boundaries") |
| 158 | + napari.run() |
| 159 | + |
| 160 | + |
| 161 | +if __name__ == "__main__": |
| 162 | + main() |
0 commit comments