7
$\begingroup$

I am trying to do color separation on this image using ClusteringComponents function (following an example on Wolfram Mathematica webpage). I will like to have a legend identifying each segmented component as "a" to "e". For example, using the original code,

ClusteringComponents[image, 5] // Colorize 

I could group black and green beads as "dark green->a". However, if I replace 5 with 6, I should be able to separate black from green beads so that I now have a legend like: Grey->"a" dark green->"b" and so on!

You kind suggestions and recommendations would be greatly appreciated. Happy Holidays guys!

$\endgroup$

1 Answer 1

10
$\begingroup$

You can accomplish this by setting the ColorRules option for Colorize and creating a legend.

colorRules = Thread[Range[7] -> Table[RandomColor[], 7]] legend = SwatchLegend[Values@colorRules, Keys@colorRules] Legended[Colorize[ClusteringComponents[image, 7], ColorRules -> colorRules], legend] 

enter image description here enter image description here

(replacing Keys@colorRules with {"a", "b", "c", "d", "e"} would change the labels from numbers to those letters, of course)

You can use different colour schemes from ColorData like so:

colorRules = Thread[Range[7] -> Table[ColorData[{"Rainbow", {0, 7}}][n], {n, 7}]] 

(using the second argument to set a min/max for the scale - you can avoid having to do that if you use an "Indexed" color scheme. Check the ColorData docs for more)

or with the function Hue like so:

colorRules = Thread[Range[7] -> Table[Hue[Rescale[n, {0, 7}]], {n, 7}]] 
$\endgroup$
2
  • $\begingroup$ Worked perfectly. I really appreciate this. Is it possible to replace "RandomColor" with some colorfunction such as "Hue"? $\endgroup$ Commented Jan 4, 2022 at 11:17
  • 1
    $\begingroup$ Yep, see my edit. $\endgroup$ Commented Jan 4, 2022 at 12:31

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.