Skip to content

Inference

from tifffile import imread

from napari_cellseg3d.config import ModelInfo
from napari_cellseg3d.dev_scripts import remote_inference as cs3d

image = imread("examples/c5image.tif")

config = cs3d.CONFIG  # InferenceWorkerConfig with defaults for a single volume
config.model_info = ModelInfo(name="SwinUNetR", model_input_size=64, num_classes=2)

results = cs3d.inference_on_images(image, config=config)

labels, stats = cs3d.post_processing(
    results[0].semantic_segmentation,
    config=cs3d.PostProcessConfig(),
)

For WNet3D, pass results[0].semantic_segmentation[1] to post_processing.

Functions

napari_cellseg3d.dev_scripts.remote_inference.inference_on_images

inference_on_images(image: array, config: InferenceWorkerConfig = CONFIG)

This function provides inference on an image with minimal config.

Parameters:

Name Type Description Default
image array

Image to perform inference on.

required
config InferenceWorkerConfig

Config for InferenceWorker. Defaults to CONFIG, see above.

CONFIG
Source code in napari_cellseg3d/dev_scripts/remote_inference.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def inference_on_images(image: np.array, config: InferenceWorkerConfig = CONFIG):
    """This function provides inference on an image with minimal config.

    Args:
        image (np.array): Image to perform inference on.
        config (InferenceWorkerConfig, optional): Config for InferenceWorker. Defaults to CONFIG, see above.
    """
    # instance_method = InstanceSegmentationWrapper(voronoi_otsu, {"spot_sigma": 0.7, "outline_sigma": 0.7})

    config.post_process_config.zoom.enabled = False
    config.post_process_config.thresholding.enabled = (
        False  # will need to be enabled and set to 0.5 for the test images
    )
    config.post_process_config.instance = InstanceSegConfig(
        enabled=False,
    )

    config.layer = image

    log = LogFixture()
    worker = InferenceWorker(config)
    logger.debug(f"Worker config: {worker.config}")

    worker.log_signal.connect(log.print_and_log)
    worker.warn_signal.connect(log.warn)
    worker.error_signal.connect(log.error)

    worker.log_parameters()

    results = []
    # append the InferenceResult when yielded by worker to results
    for result in worker.inference():
        results.append(result)

    return results

napari_cellseg3d.dev_scripts.remote_inference.post_processing

post_processing(semantic_segmentation, config: PostProcessConfig = None)

Run post-processing on inference results.

Source code in napari_cellseg3d/dev_scripts/remote_inference.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def post_processing(semantic_segmentation, config: PostProcessConfig = None):
    """Run post-processing on inference results."""
    config = PostProcessConfig() if config is None else config
    # if config.anisotropy_correction is None:
    # config.anisotropy_correction = [1, 1, 1 / 5]
    if config.anisotropy_correction is None:
        config.anisotropy_correction = [1, 1, 1]

    image = semantic_segmentation
    # apply threshold to semantic segmentation
    logger.info(f"Thresholding with {config.threshold}")
    image = threshold(image, config.threshold)
    logger.debug(f"Thresholded image shape: {image.shape}")
    # remove artifacts by clearing large objects
    logger.info(f"Clearing large objects with {config.clear_large_objects}")
    image = clear_large_objects(image, config.clear_large_objects)
    # run instance segmentation
    logger.info(
        f"Running instance segmentation with {config.spot_sigma} and {config.outline_sigma}"
    )
    labels = voronoi_otsu(
        image,
        spot_sigma=config.spot_sigma,
        outline_sigma=config.outline_sigma,
    )
    # clear small objects
    logger.info(f"Clearing small objects with {config.clear_small_size}")
    labels = clear_small_objects(labels, config.clear_small_size).astype(np.uint16)
    logger.debug(f"Labels shape: {labels.shape}")
    # get volume stats WITH ANISOTROPY
    logger.debug(f"NUMBER OF OBJECTS: {np.max(np.unique(labels)) - 1}")
    stats_not_resized = volume_stats(labels)
    ######## RUN WITH ANISOTROPY ########
    result_dict = {}
    result_dict["Not resized"] = {
        "labels": labels,
        "stats": stats_not_resized,
    }

    if config.anisotropy_correction != [1, 1, 1]:
        logger.info("Resizing image to correct anisotropy")
        image = resize(image, config.anisotropy_correction)
        logger.debug(f"Resized image shape: {image.shape}")
        logger.info("Running labels without anisotropy")
        labels_resized = voronoi_otsu(
            image,
            spot_sigma=config.isotropic_spot_sigma,
            outline_sigma=config.isotropic_outline_sigma,
        )
        logger.info(f"Clearing small objects with {config.clear_large_objects}")
        labels_resized = clear_small_objects(
            labels_resized, config.clear_small_size
        ).astype(np.uint16)
        logger.debug(f"NUMBER OF OBJECTS: {np.max(np.unique(labels_resized)) - 1}")
        logger.info("Getting volume stats without anisotropy")
        stats_resized = volume_stats(labels_resized)
        return labels_resized, stats_resized

    return labels, stats_not_resized

napari_cellseg3d.dev_scripts.remote_inference.PostProcessConfig dataclass

Config for post-processing.

Source code in napari_cellseg3d/dev_scripts/remote_inference.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
@dataclass
class PostProcessConfig:
    """Config for post-processing."""

    threshold: float = 0.4
    spot_sigma: float = 0.55
    outline_sigma: float = 0.55
    isotropic_spot_sigma: float = 0.2
    isotropic_outline_sigma: float = 0.2
    anisotropy_correction: List[float] = (
        None  # TODO change to actual values, should be a ratio like [1,1/5,1]
    )
    clear_small_size: int = 5
    clear_large_objects: int = 500

Configuration and worker