1

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

example

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?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
M.R.
  • 31,425
  • 8
  • 90
  • 281

2 Answers2

1

Maybe this way?

Legended[
 Colorize[ImageData[Binarize[Rasterize@Graphics@Annulus[]]]],
 SwatchLegend[
  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.

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
1

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

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574