# How to nicely label the colors in Colorize?

I have an image segmentation and I'd like to label with a SwatchLegend[]. Here's a MWE:

SwatchLegend[Colorize[ImageData[Rasterize@Graphics@Annulus[], "Bit"]], {"0", "1"}]


The second example from the Colorize reference page:

cols = Range[Max[labels] + 1];
Legended[Colorize[labels],
SwatchLegend[Map[RGBColor, ImageData[Colorize[{cols}]][[1]]], cols]]


Is there a solution that doesn't entail manually extracting the colors? How would one label the color regions with callouts or other labeling techniques?

Maybe this way?

Legended[
Colorize[ImageData[Binarize[Rasterize@Graphics@Annulus[]]]],
SwatchLegend[
Map[RGBColor, ImageData[Colorize[{{0, 1}}]][[1]]], {"0", "1"}]
]


I think Colorize expects a rank-two array of integers for two-dimensional images. Colorize is typically used as postprocessor of MorphologicalComponents and that returns precisely such matrices. Your ImageData was a of rank 3, the lowest level being for the color channels. So that might have provoked Mathematica to assume the image were 3D.

• That's exactly what I was hoping to avoid, but I think it might be the only way :( – M.R. Apr 26 '18 at 22:09

Using Stefan's answer to this question:

Colorize; (* force autoloading *)

img = Import["https://i.stack.imgur.com/e6aAs.png"]


labels = MorphologicalComponents[img];
ll = Select[Union[Flatten[labels]], Positive];

cols = RGBColor[ImageColorOperationsDumphashcolor[#]/255] & /@ ll;

Legended[Colorize[labels, ImageSize -> Medium], SwatchLegend[cols, ll]]