haesleinhuepf / napari-accelerated-pixel-and-object-classification

GPU-accelerated, OpenCL-based Random Forest Classifiers for pixel and labeled object classification in napari.
BSD 3-Clause "New" or "Revised" License
43 stars 7 forks source link

Result layer of train probability mapper cannot be added to the viewer because data contains float #14

Closed lazigu closed 2 years ago

lazigu commented 2 years ago

Hi Robert @haesleinhuepf,

I am encountering an error when running Train Probability Mapper. The error I get is below and I´m opening a PR to change return type annotation for the train probability mapper function, which fixes this.

TypeError: Only integer types are supported for Labels layers, but data contains float32. (Expand for a full traceback) C:\Users\lazi257c\Miniconda3\envs\apoc\lib\site-packages\pyopencl\array.py:878: UserWarning: str.__repr__ was expected to return a string starting with 'array', got '", ], key='Train_probability_mapper result') 144 try: --> 145 return self.__getitem__(self.index(key)) key = 'Train_probability_mapper result' self = [, ] 146 except ValueError as e: File ~\Miniconda3\envs\apoc\lib\site-packages\napari\utils\events\containers\_typed.py:238, in TypedMutableSequence.index(self=[, ], value='Train_probability_mapper result', start=0, stop=None) 236 return i --> 238 raise ValueError( trans = value = 'Train_probability_mapper result' 239 trans._( 240 "{value!r} is not in list", 241 deferred=True, 242 value=value, 243 ) 244 ) ValueError: 'Train_probability_mapper result' is not in list The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) File ~\Miniconda3\envs\apoc\lib\site-packages\napari\utils\_magicgui.py:71, in add_layer_data_to_viewer(gui= napari.types.LabelsData>, result= (70, 378, 401) float32, return_type=napari.types.LabelsData) 70 try: ---> 71 viewer.layers[gui.result_name].data = result viewer = Viewer(axes=Axes(visible=False, labels=True, colored=True, dashed=False, arrows=True), camera=Camera(center=(0.0, 169.57705271313824, 147.27081148422315), zoom=3.1991526133894514, angles=(0.0, 0.0, 90.0), perspective=0.0, interactive=True), cursor=Cursor(position=(35.0, 153.79161720344558, 230.26153083356292), scaled=True, size=5, style=), dims=Dims(ndim=3, ndisplay=2, last_used=0, range=((0.0, 70.0, 1.0), (0.0, 378.0, 1.0), (0.0, 401.0, 1.0)), current_step=(35, 189, 200), order=(0, 1, 2), axis_labels=('0', '1', '2')), grid=GridCanvas(stride=1, shape=(-1, -1), enabled=False), layers=[, ], scale_bar=ScaleBar(visible=False, colored=False, ticks=True, position=, font_size=10, unit=None), text_overlay=TextOverlay(visible=False, color=(0.5, 0.5, 0.5, 1.0), font_size=10, position=, text=''), overlays=Overlays(interaction_box=InteractionBox(points=None, show=False, show_handle=False, show_vertices=False, selection_box_drag=None, selection_box_final=None, transform_start=, transform_drag=, transform_final=, transform=, allow_new_selection=True, selected_vertex=None)), help='enter paint or fill mode to edit labels', status='Labels [ 35 154 230]: 0', tooltip=Tooltip(visible=False, text=''), theme='dark', title='napari', mouse_move_callbacks=[.mouse_move at 0x000001D79AFBF0A0>], mouse_drag_callbacks=[.mouse_drag at 0x000001D79AFBE950>], mouse_double_click_callbacks=[], mouse_wheel_callbacks=[], _persisted_mouse_event={}, _mouse_drag_gen={}, _mouse_wheel_gen={}, keymap={'Shift': .hold_to_lock_aspect_ratio at 0x000001D79AF2A9E0>, 'Control-Shift-R': , 'Control-Shift-A': }) result = (70, 378, 401) float32 gui = (70, 378, 401) uint16, annotation: napari.types.LabelsData = (70, 378, 401) int32, model_filename: str = 'ProbabilityMapper.cl', featureset: apoc._feature_sets.PredefinedFeatureSet = , custom_features: str = 'original gaussian_blur=1 sobel_of_gaussian_blur=1', output_probability_of_class: int = 2, max_depth: int = 2, num_ensembles: int = 10) -> napari.types.LabelsData> viewer.layers = [, ] 72 except KeyError: File ~\Miniconda3\envs\apoc\lib\site-packages\napari\utils\events\containers\_typed.py:147, in TypedMutableSequence.__getitem__(self=[, ], key='Train_probability_mapper result') 146 except ValueError as e: --> 147 raise KeyError(str(e)) from e 149 result = self._list[key] KeyError: "'Train_probability_mapper result' is not in list" During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) File ~\Miniconda3\envs\apoc\lib\site-packages\magicgui\widgets\_bases\value_widget.py:57, in ValueWidget._on_value_change(self=PushButton(value=False, annotation=None, name='call_button'), value=False) 55 if value is self.null_value and not self._nullable: 56 return ---> 57 self.changed.emit(value) value = False self.changed = self = PushButton(value=False, annotation=None, name='call_button') File ~\Miniconda3\envs\apoc\lib\site-packages\psygnal\_signal.py:682, in psygnal._signal.SignalInstance.emit() File ~\Miniconda3\envs\apoc\lib\site-packages\psygnal\_signal.py:724, in psygnal._signal.SignalInstance._run_emit_loop() File ~\Miniconda3\envs\apoc\lib\site-packages\psygnal\_signal.py:725, in psygnal._signal.SignalInstance._run_emit_loop() File ~\Miniconda3\envs\apoc\lib\site-packages\psygnal\_signal.py:745, in psygnal._signal.SignalInstance._run_emit_loop() File ~\Miniconda3\envs\apoc\lib\site-packages\magicgui\widgets\_function_gui.py:201, in FunctionGui.__init__.._disable_button_and_call() 199 self._call_button.enabled = False 200 try: --> 201 self.__call__() self = (70, 378, 401) uint16, annotation: napari.types.LabelsData = (70, 378, 401) int32, model_filename: str = 'ProbabilityMapper.cl', featureset: apoc._feature_sets.PredefinedFeatureSet = , custom_features: str = 'original gaussian_blur=1 sobel_of_gaussian_blur=1', output_probability_of_class: int = 2, max_depth: int = 2, num_ensembles: int = 10) -> napari.types.LabelsData> 202 finally: 203 self._call_button.enabled = True File ~\Miniconda3\envs\apoc\lib\site-packages\magicgui\widgets\_function_gui.py:319, in FunctionGui.__call__(self= napari.types.LabelsData>, update_widget=False, *args=(), **kwargs={}) 316 from magicgui.type_map import _type2callback 318 for callback in _type2callback(return_type): --> 319 callback(self, value, return_type) return_type = napari.types.LabelsData value = (70, 378, 401) float32 self = (70, 378, 401) uint16, annotation: napari.types.LabelsData = (70, 378, 401) int32, model_filename: str = 'ProbabilityMapper.cl', featureset: apoc._feature_sets.PredefinedFeatureSet = , custom_features: str = 'original gaussian_blur=1 sobel_of_gaussian_blur=1', output_probability_of_class: int = 2, max_depth: int = 2, num_ensembles: int = 10) -> napari.types.LabelsData> callback = 320 self.called.emit(value) 321 return value File ~\Miniconda3\envs\apoc\lib\site-packages\napari\utils\_magicgui.py:75, in add_layer_data_to_viewer(gui= napari.types.LabelsData>, result= (70, 378, 401) float32, return_type=napari.types.LabelsData) 73 layer_type = return_type.__name__.replace("Data", "").lower() 74 adder = getattr(viewer, f'add_{layer_type}') ---> 75 adder(data=result, name=gui.result_name) result = (70, 378, 401) float32 gui = (70, 378, 401) uint16, annotation: napari.types.LabelsData = (70, 378, 401) int32, model_filename: str = 'ProbabilityMapper.cl', featureset: apoc._feature_sets.PredefinedFeatureSet = , custom_features: str = 'original gaussian_blur=1 sobel_of_gaussian_blur=1', output_probability_of_class: int = 2, max_depth: int = 2, num_ensembles: int = 10) -> napari.types.LabelsData> adder = ), dims=Dims(ndim=3, ndisplay=2, last_used=0, range=((0.0, 70.0, 1.0), (0.0, 378.0, 1.0), (0.0, 401.0, 1.0)), current_step=(35, 189, 200), order=(0, 1, 2), axis_labels=('0', '1', '2')), grid=GridCanvas(stride=1, shape=(-1, -1), enabled=False), layers=[, ], scale_bar=ScaleBar(visible=False, colored=False, ticks=True, position=, font_size=10, unit=None), text_overlay=TextOverlay(visible=False, color=(0.5, 0.5, 0.5, 1.0), font_size=10, position=, text=''), overlays=Overlays(interaction_box=InteractionBox(points=None, show=False, show_handle=False, show_vertices=False, selection_box_drag=None, selection_box_final=None, transform_start=, transform_drag=, transform_final=, transform=, allow_new_selection=True, selected_vertex=None)), help='enter paint or fill mode to edit labels', status='Labels [ 35 154 230]: 0', tooltip=Tooltip(visible=False, text=''), theme='dark', title='napari', mouse_move_callbacks=[.mouse_move at 0x000001D79AFBF0A0>], mouse_drag_callbacks=[.mouse_drag at 0x000001D79AFBE950>], mouse_double_click_callbacks=[], mouse_wheel_callbacks=[], _persisted_mouse_event={}, _mouse_drag_gen={}, _mouse_wheel_gen={}, keymap={'Shift': .hold_to_lock_aspect_ratio at 0x000001D79AF2A9E0>, 'Control-Shift-R': , 'Control-Shift-A': })> File ~\Miniconda3\envs\apoc\lib\site-packages\napari\components\viewer_model.py:4, in add_labels(self=Viewer(axes=Axes(visible=False, labels=True, col...._transform_active_layer at 0x000001D79AF78670>}), data= (70, 378, 401) float32, num_colors=50, features=None, properties=None, color=None, seed=0.5, name='Train_probability_mapper result', metadata=None, scale=None, translate=None, rotate=None, shear=None, affine=None, opacity=0.7, blending='translucent', rendering='iso_categorical', depiction='volume', visible=True, multiscale=None, cache=True, plane=None, experimental_clipping_planes=None) 1 from __future__ import annotations 3 import inspect ----> 4 import itertools 5 import os 6 import warnings File ~\Miniconda3\envs\apoc\lib\site-packages\napari\layers\labels\labels.py:259, in Labels.__init__(self= instance, data= (70, 378, 401) float32, num_colors=50, features=None, properties=None, color=None, seed=0.5, name='Train_probability_mapper result', metadata=None, scale=None, translate=None, rotate=None, shear=None, affine=None, opacity=0.7, blending='translucent', rendering='iso_categorical', depiction='volume', visible=True, multiscale=None, cache=True, plane=None, experimental_clipping_planes=None) 256 self._show_selected_label = False 257 self._contour = 0 --> 259 data = self._ensure_int_labels(data) data = (70, 378, 401) float32 Exception trying to inspect frame. No more locals available. 260 self._color_lookup_func = None 262 super().__init__( 263 data, 264 rgb=False, (...) 284 experimental_clipping_planes=experimental_clipping_planes, 285 ) File ~\Miniconda3\envs\apoc\lib\site-packages\napari\layers\labels\labels.py:562, in Labels._ensure_int_labels(self= instance, data=[ (70, 378, 401) float32]) 558 for data_level in data: 559 # normalize_dtype turns e.g. tensorstore or torch dtypes into 560 # numpy dtypes 561 if np.issubdtype(normalize_dtype(data_level.dtype), np.floating): --> 562 raise TypeError( trans = data_level = (70, 378, 401) float32 data_level.dtype = dtype('float32') 563 trans._( 564 "Only integer types are supported for Labels layers, but data contains {data_level_type}.", 565 data_level_type=data_level.dtype, 566 ) 567 ) 568 if data_level.dtype == bool: 569 int_data.append(data_level.astype(np.int8)) TypeError: Only integer types are supported for Labels layers, but data contains float32.

Best, Laura