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$
    – Dean
    Jan 4, 2022 at 11:17
  • 1
    $\begingroup$ Yep, see my edit. $\endgroup$
    – Carl Lange
    Jan 4, 2022 at 12:31

Your Answer

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

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