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];
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?


2 Answers 2


Maybe this way?

  Map[RGBColor, ImageData[Colorize[{{0, 1}}]][[1]]], {"0", "1"}]

enter image description here

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.

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

Using Stefan's answer to this question:

Colorize; (* force autoloading *)

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

test image

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

cols = RGBColor[Image`ColorOperationsDump`hashcolor[#]/255] & /@ ll;

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

colorization with legends


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.