Certain layers mysteriously invisible when removing then re-adding layers

I’m making a viewer to manually annotate images, and need to repeatedly repopulate layers with different data. I’m running into a strange issue where a layer is mysteriously invisible. Any suggestions? Minimal code below:

import napari
import numpy as np

with napari.gui_qt():
    viewer = napari.Viewer()
    image = np.random.rand(1000,1000)
    points = np.random.rand(100, 2) * 1000
    shapes = [np.random.rand(10,2) * 1000 for x in range(10)]
    
    viewer.add_image(image)
    viewer.add_shapes(shapes, shape_type='polygon')
    viewer.add_points(points)

    # remove and re-add image    
    viewer.layers.remove('image')
    viewer.add_image(image, name='image')
    
    # remove non-image data
    viewer.layers.remove('shapes')
    viewer.layers.remove('points')
    # add it back
    viewer.add_shapes(shapes, shape_type='polygon')
    viewer.add_points(points)
   # and mysteriously, shapes is not visible

Any idea why this might be? Strangely, it also seems like if I permute the last four lines like so, I don’t have this problem (but in my actual use case this is hard to do)

    viewer.layers.remove('shapes')
    viewer.add_shapes(shapes, shape_type='polygon')
    viewer.layers.remove('points')
    viewer.add_points(points)
    # this works!

Thanks in advance!

this definitely looks like a bug. Looks like for some reason the order of the visuals (like, the “z-index” of what layer goes in front) is not updating properly. Just to point out the bug explicitly here, after running the code example, if you run…

[viewer.window.qt_viewer.layer_to_visual[x].order for x in viewer.layers]
# output is [3,2,3] ... so two layers erroneously have the same value

@sofroniewn might have a suggestion for a quick workaround, but we’ll likely need to fix this on our end

1 Like

It appears this was fixed upon upgrading from 0.3.5 to 0.3.6 - thanks!!

3 Likes

Great! Yes, was fixed by https://github.com/napari/napari/pull/1463 - thanks for making the bug report!!

1 Like