Specify labels colors

Hi @sofroniewn, @jni,

(napari is so useful I’m finding a third platform to ask questions)

I use viewer.add_labels in the normal way to view segmentations etc., and the random colors work nicely. However, I also want to use it to overlay lines (as a specific color) onto the image. The lines are actually a binary image, and so (I think) I can choose between:

  • Use viewer.add_image which allows me to choose a colormap, but then I have to play around with opacity etc to see the image beneath the 0 elements.
  • Use viewer.add_labels, which draws the lines nicely, without worrying about opacity of the 0 elements, but I have to shuffle colors to get one that works for me.

Is there a way of using viewer.add_labels view a single “label” and specify the color (or another way to get what I need)?


Hi @adamltyson - at least you use the same handle on each platform :rofl::rofl:

Probably the fastest and easiest is to use add_image with a custom color map - these are very easy to make using vispy and we should document them better. Here is a minimal example:

import numpy as np
from skimage import data
from vispy.color import Colormap
import napari

blobs = data.binary_blobs(length=64, n_dim=2, volume_fraction=0.1)
rand = np.random.random((64, 64))

with napari.gui_qt():
    label_red = Colormap([[0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 1.0]])
    viewer = napari.view_image(rand)
    viewer.add_image(blobs, contrast_limits=[0, 1], colormap=('label_red', label_red))

Note here that to define the color map I used RGBA where A is the alpha that goes from 0 to 1.

This does seem like a common use case though, and we have in the past discussed providing a list of colors to add_labels such that if you wanted red, blue, and yellow labels you’d get them. We have to make sure we don’t take performance hits when painting, but I think that would be nice, especially if you might want to edit those labels (which you won’t be able to do with you Image layer).

1 Like

I have raised an issue on the repo for supporting custom colors with Labels so you can have features like painting and fill during this usage.

Perfect, thanks! I forgot about using a transparent colormap.

1 Like