Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Does anyone know the syntax to DistanceFunction? I am trying to define my own function to use with ClusteringComponents; e.g.,

ClusteringComponents[img, DistanceFunction -> (Norm[#1 - #2] &)]

Needless to say it does not work as shown (it overflows for some reason). I also tried using ImageData@img but that does not even terminate.

share|improve this question
AT least in V8.0 ClusteringComponents[]doesn't seem to accept a custom DistanceFunction. Just those listed in the help – Dr. belisarius Jan 25 '13 at 8:06

I tested ClusteringComponents with the examples provided in the Documentation Center ( of Mathematica. In Options > DistanceFunction there is an example provided how to use your own DistanceFunction in ClusteringComponents:

ClusteringComponents[{{1, 2}, 3, {10, 11}, {12, {13}}, 14}, 2, 1, 
     DistanceFunction -> (Abs[Length[#1] - Length[#2]] &)]

I tried to apply this to an image without any success. I only ended up with some very strange looking error messages. After a few more tests I found the following solution. First of all, ClusteringComponents seems to work with a selfmade DistanceFunction only if you provide it with ImageData of a grayscale image. The following approach works:

Colorize@ClusteringComponents[ImageData[ColorConvert[img, "GrayScale"]], 3, 
  DistanceFunction -> (Norm[#1 - #2] &)]

enter image description here enter image description here

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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