diff --git a/napari_cellseg3d/_tests/test_inference.py b/napari_cellseg3d/_tests/test_inference.py index 4bdc51fa..f18ad779 100644 --- a/napari_cellseg3d/_tests/test_inference.py +++ b/napari_cellseg3d/_tests/test_inference.py @@ -105,3 +105,62 @@ def test_post_processing(): assert results.shape == (2, 64, 64, 64) worker.stats_csv(np.squeeze(labels)) + + +def test_select_channel(): + worker = InferenceWorker(worker_config=InferenceWorkerConfig()) + multi = rand_gen.random((3, 4, 4, 4)) + single = rand_gen.random((4, 4, 4)) + + assert worker.select_channel(multi) is multi # keep_channel unset + + warnings = [] + worker.warn_signal.connect(warnings.append) + + worker.config.keep_channel = 1 + np.testing.assert_array_equal(worker.select_channel(multi), multi[1]) + assert worker.select_channel(None) is None + assert warnings == [] + + assert worker.select_channel(single) is single # no channel axis + assert len(warnings) == 1 + + worker.config.keep_channel = 3 # out of range: keep all channels + assert worker.select_channel(multi) is multi + assert worker.select_channel(multi) is multi + assert len(warnings) == 1 # warned once per worker + + worker = InferenceWorker(worker_config=InferenceWorkerConfig(keep_channel=3)) + worker.warn_signal.connect(warnings.append) + assert worker.select_channel(multi) is multi + assert len(warnings) == 2 + assert "3 channels" in warnings[-1] + + +def test_inference_on_folder_keep_channel(): + config = InferenceWorkerConfig(keep_channel=1) + config.images_filepaths = [str(Path(__file__).resolve().parent / "res/test.tif")] + + class two_channels: + @staticmethod + def eval(): + return True + + def __call__(self, x): + x = torch.Tensor(x) + return torch.cat([x, 1 - x], dim=-4) # (N, 2, H, W, D) + + class identity: + def __call__(self, x): + return torch.Tensor(x) + + worker = InferenceWorker(worker_config=config) + worker.aniso_transform = identity() + image = torch.Tensor(rand_gen.random(size=(1, 1, 8, 8, 8))) + res = worker.inference_on_folder( + {"image": image}, + 0, + model=two_channels(), + post_process_transforms=identity(), + ) + assert res.semantic_segmentation.shape == (8, 8, 8) diff --git a/napari_cellseg3d/_tests/test_model_wnet.py b/napari_cellseg3d/_tests/test_model_wnet.py new file mode 100644 index 00000000..a37be2e3 --- /dev/null +++ b/napari_cellseg3d/_tests/test_model_wnet.py @@ -0,0 +1,27 @@ +import torch + +from napari_cellseg3d.code_models.models.model_WNet import WNet_ +from napari_cellseg3d.code_models.models.wnet.model import WNet + + +def test_num_classes_from_weights(tmp_path): + weights = tmp_path / "wnet_3_classes.pth" + torch.save(WNet(num_classes=3).state_dict(), weights) + assert WNet_.num_classes_from_weights(weights) == 3 + + model = WNet_(out_channels=3) + model.load_state_dict(torch.load(weights, weights_only=True), strict=True) + + +def test_num_classes_from_weights_unreadable(tmp_path): + assert WNet_.num_classes_from_weights(tmp_path / "missing.pth") is None + assert WNet_.num_classes_from_weights(tmp_path / "model.onnx") is None + no_key = tmp_path / "other.pth" + torch.save({"weight": torch.zeros(1)}, no_key) + assert WNet_.num_classes_from_weights(no_key) is None + garbage = tmp_path / "garbage.pth" + garbage.write_bytes(b"not a checkpoint") + assert WNet_.num_classes_from_weights(garbage) is None + pickled_model = tmp_path / "pickled_model.pth" + torch.save(torch.nn.Conv3d(1, 2, 1), pickled_model) + assert WNet_.num_classes_from_weights(pickled_model) is None diff --git a/napari_cellseg3d/_tests/test_plugin_inference.py b/napari_cellseg3d/_tests/test_plugin_inference.py index 03565045..de00d7a5 100644 --- a/napari_cellseg3d/_tests/test_plugin_inference.py +++ b/napari_cellseg3d/_tests/test_plugin_inference.py @@ -91,3 +91,58 @@ def test_inference(make_napari_viewer_proxy, qtbot): # widget.worker.start() assert widget.on_finish() + + +def test_keep_channel_choice(make_napari_viewer_proxy, tmp_path): + import torch + + from napari_cellseg3d import interface as ui + from napari_cellseg3d.code_models.models.wnet.model import WNet + + # fresh widget, not the singleton instance closed by test_inference + ui.QWidgetSingleton._instances.pop(Inferer, None) + viewer = make_napari_viewer_proxy() + widget = Inferer(viewer) + + widget.model_choice.setCurrentText("SegResNet") + assert widget.keep_channel_choice.isHidden() + assert widget._set_worker_config().keep_channel is None + + widget.model_choice.setCurrentText("WNet3D") + assert not widget.keep_channel_choice.isHidden() + assert widget.channel_choice_container.isHidden() + assert widget.channel_choice.count() == 2 + + widget.keep_channel_choice.setChecked(True) + assert not widget.channel_choice_container.isHidden() + assert widget.channel_choice.currentIndex() == 1 # pretrained foreground + worker_config = widget._set_worker_config() + assert worker_config.keep_channel == 1 + assert worker_config.model_info.num_classes == 2 + + weights = tmp_path / "wnet_3_classes.pth" + torch.save(WNet(num_classes=3).state_dict(), weights) + widget.weights_config.path = str(weights) + widget.custom_weights_choice.setChecked(True) + assert widget.channel_choice.count() == 3 + assert widget.channel_choice.currentIndex() == 1 # kept when still valid + widget.channel_choice.setCurrentIndex(2) + worker_config = widget._set_worker_config() + assert worker_config.keep_channel == 2 + assert worker_config.model_info.num_classes == 3 + + widget.weights_config.path = str(tmp_path / "wnet.onnx") + widget._update_wnet_num_classes() + assert not widget.keep_channel_choice.isEnabled() + assert not widget.keep_channel_choice.isChecked() + assert widget.channel_choice_container.isHidden() + assert widget._set_worker_config().keep_channel is None + + widget.custom_weights_choice.setChecked(False) + assert widget.keep_channel_choice.isEnabled() + widget.keep_channel_choice.setChecked(True) + assert widget.channel_choice.count() == 2 + assert widget.channel_choice.currentIndex() == 1 # pretrained foreground + + widget.keep_channel_choice.setChecked(False) + assert widget._set_worker_config().keep_channel is None diff --git a/napari_cellseg3d/code_models/models/model_WNet.py b/napari_cellseg3d/code_models/models/model_WNet.py index 2e4c29b1..fd5837ed 100644 --- a/napari_cellseg3d/code_models/models/model_WNet.py +++ b/napari_cellseg3d/code_models/models/model_WNet.py @@ -3,10 +3,20 @@ .. important:: Used for inference only. For training the base class is used. """ +import pickle +from pathlib import Path +from typing import Optional + +import torch + # local from napari_cellseg3d.code_models.models.wnet.model import WNet_encoder +from napari_cellseg3d.utils import LOGGER as logger from napari_cellseg3d.utils import remap_image +NUM_CLASSES_KEY = "encoder.out_b.module.8.bias" +"""State-dict key of the encoder's final conv bias, whose length is the number of classes.""" + class WNet_(WNet_encoder): """W-Net wrapper for napari_cellseg3d. @@ -16,6 +26,8 @@ class WNet_(WNet_encoder): weights_file = "wnet_latest.pth" default_threshold = 0.6 + default_channel = 1 + """Foreground channel of the pretrained weights.""" def __init__( self, @@ -46,6 +58,24 @@ def forward(self, x): norm_x = remap_image(x) return super().forward(norm_x) + @staticmethod + def num_classes_from_weights(weights_path) -> Optional[int]: + """Number of encoder output classes stored in a .pth weights file, or None if it cannot be read.""" + if Path(weights_path).suffix != ".pth": + return None + try: + state_dict = torch.load(weights_path, map_location="cpu", weights_only=True) + return int(state_dict[NUM_CLASSES_KEY].shape[0]) + except ( + OSError, + RuntimeError, + KeyError, + AttributeError, + pickle.UnpicklingError, + ) as e: + logger.debug(f"Could not read number of classes from {weights_path}: {e}") + return None + def load_state_dict(self, state_dict, strict=True): """Load the model state dict for inference, without the decoder weights.""" encoder_checkpoint = state_dict.copy() diff --git a/napari_cellseg3d/code_models/worker_inference.py b/napari_cellseg3d/code_models/worker_inference.py index 444856a5..13eaebb8 100644 --- a/napari_cellseg3d/code_models/worker_inference.py +++ b/napari_cellseg3d/code_models/worker_inference.py @@ -107,6 +107,7 @@ def __init__( self.error_signal = self._signals.error_signal self.config = worker_config + self._keep_channel_warned = False """These attributes are all arguments of :py:func:~inference, please see that for reference""" @@ -169,6 +170,8 @@ def log_parameters(self): self.log("Parameters summary :") self.log(f"Model is : {config.model_info.name}") + if config.keep_channel is not None: + self.log(f"Keeping only channel {config.keep_channel}") if config.post_process_config.thresholding.enabled: self.log( f"Thresholding is enabled at {config.post_process_config.thresholding.threshold_value}" @@ -644,6 +647,8 @@ def inference_on_folder(self, inf_data, i, model, post_process_transforms): logger.debug( f"Output shape {out.shape[-3:]} does not match input shape {inputs_shape_corrected[-3:]} on HWD dims even after rotation" ) + out_all_channels = out + out = self.select_channel(out) self.save_image(out, i=i) instance_labels, stats = self.get_instance_result(out, i=i) if self.config.use_crf: @@ -651,7 +656,7 @@ def inference_on_folder(self, inf_data, i, model, post_process_transforms): try: crf_results = self.run_crf( crf_in, - out, + out_all_channels, aniso_transform=self.aniso_transform, image_id=i, ) @@ -675,6 +680,32 @@ def inference_on_folder(self, inf_data, i, model, post_process_transforms): i=i, ) + def select_channel(self, array): + """Keeps only channel :py:attr:`config.keep_channel` of a (C, H, W, D) array. + + Returned unchanged if ``keep_channel`` is unset, the array has no channel axis, + or the channel does not exist; the latter two warn once per worker. + """ + channel = self.config.keep_channel + if channel is None or array is None: + return array + if len(array.shape) != 4: + self._warn_channel_once( + f"Channel {channel} requested but the output has no channel axis (shape {array.shape}); keeping the output as is" + ) + return array + if not 0 <= channel < array.shape[0]: + self._warn_channel_once( + f"Channel {channel} requested but the output has {array.shape[0]} channels; keeping all channels" + ) + return array + return array[channel] + + def _warn_channel_once(self, message): + if not self._keep_channel_warned: + self._keep_channel_warned = True + self.warn(message) + def run_crf(self, image, labels, aniso_transform, image_id=0): """Runs CRF on the image and labels.""" try: @@ -691,6 +722,7 @@ def run_crf(self, image, labels, aniso_transform, image_id=0): crf_results = crf_with_config( image, labels, config=self.config.crf_config, log=self.log ) + crf_results = self.select_channel(crf_results) self.save_image( crf_results, i=image_id, @@ -739,6 +771,8 @@ def inference_on_layer(self, image, model, post_process_transforms): logger.debug( f"Output shape {out.shape[-3:]} does not match input shape {layer_shape_corrected[-3:]} on HWD dims even after rotation" ) + out_all_channels = out + out = self.select_channel(out) self.save_image(out, from_layer=True) instance_labels, stats = self.get_instance_result( @@ -746,7 +780,7 @@ def inference_on_layer(self, image, model, post_process_transforms): ) crf_results = ( - self.run_crf(image, out, aniso_transform=self.aniso_transform) + self.run_crf(image, out_all_channels, aniso_transform=self.aniso_transform) if self.config.use_crf else None ) @@ -818,10 +852,12 @@ def inference(self): model = ONNXModelWrapper(weights_config.path) else: # assume is .pth self.log("Instantiating model...") + model_kwargs = {} + if model_name == "WNet3D": + model_kwargs["out_channels"] = self.config.model_info.num_classes model = model_class( input_img_size=[dims, dims, dims], - # device=self.config.device, - # num_classes=self.config.model_info.num_classes, + **model_kwargs, ) try: model = model.to(self.config.device) diff --git a/napari_cellseg3d/code_plugins/plugin_model_inference.py b/napari_cellseg3d/code_plugins/plugin_model_inference.py index ee990bbd..3f841f5d 100644 --- a/napari_cellseg3d/code_plugins/plugin_model_inference.py +++ b/napari_cellseg3d/code_plugins/plugin_model_inference.py @@ -17,6 +17,7 @@ InstanceWidgets, ) from napari_cellseg3d.code_models.model_framework import ModelFramework +from napari_cellseg3d.code_models.models.model_WNet import WNet_ from napari_cellseg3d.code_models.worker_inference import InferenceWorker from napari_cellseg3d.code_models.workers_utils import InferenceResult from napari_cellseg3d.code_plugins.plugin_crf import CRFParamsWidget @@ -226,6 +227,23 @@ def __init__(self, viewer: "napari.viewer.Viewer", parent=None): self.save_stats_to_csv_box = ui.CheckBox("Save stats to csv", parent=self) + # WNet3D output channel selection + self.wnet_num_classes = config.ModelInfo.num_classes + self.keep_channel_choice = ui.CheckBox( + "Keep a single channel", + func=self._toggle_display_channel_choice, + parent=self, + ) + self.channel_choice = ui.DropdownMenu( + [str(i) for i in range(self.wnet_num_classes)], text_label="Channel" + ) + self.channel_choice.setCurrentIndex(WNet_.default_channel) + self.channel_choice_container = ui.combine_blocks( + self.channel_choice, + self.channel_choice.label, + horizontal=False, + ) + ################## ################## @@ -248,6 +266,42 @@ def __init__(self, viewer: "napari.viewer.Viewer", parent=None): self._remove_unused() + def _is_wnet(self) -> bool: + return self.model_choice.currentText() == "WNet3D" + + def _update_wnet_num_classes(self): + """Reads the number of WNet3D output classes from the custom weights, and lists them in the channel choice. + + Pretrained weights select their foreground channel; custom weights keep the current channel if it still exists. + The option is disabled for custom weights whose number of classes cannot be read (.onnx, .pt, unreadable .pth). + """ + use_custom = self.custom_weights_choice.isChecked() + num_classes = None + if use_custom and self.weights_config.path: + num_classes = WNet_.num_classes_from_weights(self.weights_config.path) + channels_known = not use_custom or num_classes is not None + if not channels_known: + self.keep_channel_choice.setChecked(False) + self.keep_channel_choice.setEnabled(channels_known) + self.wnet_num_classes = ( + num_classes if num_classes is not None else config.ModelInfo.num_classes + ) + current = self.channel_choice.currentIndex() + if not use_custom: + current = WNet_.default_channel + self.channel_choice.clear() + self.channel_choice.addItems([str(i) for i in range(self.wnet_num_classes)]) + self.channel_choice.setCurrentIndex( + current if 0 <= current < self.wnet_num_classes else 0 + ) + + def _toggle_display_channel_choice(self): + """Shows the channel options only for WNet3D, and the dropdown only when the checkbox is checked.""" + self.keep_channel_choice.setVisible(self._is_wnet()) + self.channel_choice_container.setVisible( + self._is_wnet() and self.keep_channel_choice.isChecked() + ) + def _toggle_crf_choice(self): if self.model_choice.currentText() == "WNet3D": self.use_crf.setVisible(True) @@ -291,6 +345,16 @@ def _set_tooltips(self): "Percentage of overlap between windows to use when using sliding window" ) + self.keep_channel_choice.setToolTip( + "WNet3D outputs one channel per class.\n" + "Keep only the chosen channel in the saved and displayed results.\n" + "Do not use if you are not sure of which channel to keep.\n" + "Unavailable for custom .onnx or .pt weights." + ) + self.channel_choice.setToolTip( + "Output channel to keep. The number of channels is read from custom weights,\n" + "and is 2 for the pretrained WNet3D." + ) self.keep_data_on_cpu_box.setToolTip( "If enabled, data will be kept on the RAM rather than the VRAM.\nCan avoid out of memory issues with CUDA" ) @@ -397,6 +461,7 @@ def _load_weights_path(self): file_extension="Weights file (*.pth *.pt *.onnx)", ) self._update_weights_path(file) + self._update_wnet_num_classes() def _set_default_threshold(self): # Whenever a model is selected, set the default threshold from the model file @@ -517,6 +582,8 @@ def _build(self): post_proc_layout, [ self.anisotropy_wdgt, # anisotropy + self.keep_channel_choice, + self.channel_choice_container, self.thresholding_checkbox, self.thresholding_slider.container, # thresholding self.use_crf, @@ -532,6 +599,11 @@ def _build(self): self.thresholding_checkbox.setChecked(True) self._toggle_crf_choice() self.model_choice.currentIndexChanged.connect(self._toggle_crf_choice) + self._toggle_display_channel_choice() + self.model_choice.currentIndexChanged.connect( + self._toggle_display_channel_choice + ) + self.custom_weights_choice.toggled.connect(self._update_wnet_num_classes) self.model_choice.currentIndexChanged.connect(self._set_default_threshold) ModelFramework._show_io_element( self.save_stats_to_csv_box, self.use_instance_choice @@ -829,6 +901,13 @@ def _set_worker_config(self) -> config.InferenceWorkerConfig: name=self.model_choice.currentText(), model_input_size=self.model_input_size.value(), ) + if self._is_wnet(): + self.model_info.num_classes = self.wnet_num_classes + keep_channel = ( + self.channel_choice.currentIndex() + if self._is_wnet() and self.keep_channel_choice.isChecked() + else None + ) self.weights_config.use_custom = self.custom_weights_choice.isChecked() @@ -887,6 +966,7 @@ def _set_worker_config(self) -> config.InferenceWorkerConfig: sliding_window_config=window_config, use_crf=self.use_crf.isChecked(), crf_config=self.crf_widgets.make_config(), + keep_channel=keep_channel, ) return self.worker_config diff --git a/napari_cellseg3d/config.py b/napari_cellseg3d/config.py index 67d25d37..ac0ffee1 100644 --- a/napari_cellseg3d/config.py +++ b/napari_cellseg3d/config.py @@ -261,6 +261,7 @@ class InferenceWorkerConfig: sliding_window_config (SlidingWindowConfig): sliding window config images_filepaths (str): path to images to infer layer (napari.layers.Layer): napari layer to infer on + keep_channel (Optional[int]): index of the single output channel to keep for multi-channel models (WNet3D); None keeps all channels """ device: str = "cpu" @@ -279,6 +280,7 @@ class InferenceWorkerConfig: images_filepaths: List[str] = None layer: napari.layers.Layer = None + keep_channel: Optional[int] = None ####################