Page 1 of 1

How to get the dominant color in an image?

Posted: 2019-05-24T14:58:38-07:00
by GoncaloM
Hello.
I'm trying to get the dominant colour (hexa code) in an image using the Magick.NET.
How can I do this?

Re: How to get the dominant color in an image?

Posted: 2019-05-24T16:14:26-07:00
by snibgo
What do you mean by "dominant colour"? Perhaps you can link to sample images and tell us what the dominant colour is.

Re: How to get the dominant color in an image?

Posted: 2019-05-24T16:23:56-07:00
by fmw42
Scale the image to say 50x50. Then reduce colors to some small number, say 8 at 8-bit depth. The get the histogram and sort it by decreasing count and take the top one.

Sorry, I do not know Magick.NET


In unix command line:

Code: Select all

convert image -scale 50x50! -depth 8 +dither -colors 8 -format "%c" histogram:info: |\
sed -n 's/^[ ]*\(.*\):.*[#]\([0-9a-fA-F]*\) .*$/\1,#\2/p' | sort -r -n -k 1 -t ","
For example:

Code: Select all

convert logo: -scale 50x50! -depth 8 +dither -colors 8 -format "%c" histogram:info: |\
sed -n 's/^[ ]*\(.*\):.*[#]\([0-9a-fA-F]*\) .*$/\1,#\2/p' | sort -r -n -k 1 -t ","
1975,#FEFEFE
117,#3F435E
93,#E1D9CF
87,#223D8F
84,#BEA7A3
59,#CE6357
54,#59668A
31,#AB9765

Code: Select all

convert -size 100x100 xc:"#FEFEFE" dominant.gif
So the dominant color is #FEFEFE, which is near white as expected from the logo: image.


See my bash unix shell script, dominantcolor, at my link below for examples.

Re: How to get the dominant color in an image?

Posted: 2019-05-25T06:03:32-07:00
by GoncaloM
snibgo wrote: 2019-05-24T16:14:26-07:00 What do you mean by "dominant colour"? Perhaps you can link to sample images and tell us what the dominant colour is.
Hello.

The dominant colour is the colour that appears more times on an image, just like fmw42 shown.
I just wanted to know how to do it using Magick.NET.

Re: How to get the dominant color in an image?

Posted: 2019-05-25T06:48:58-07:00
by GoncaloM
Hello everyone.

I was able to implement it so here's the code if someone else needs to perform this action.

Code: Select all

using (MagickImage image = new MagickImage(ssimageBinary))
{
	Dictionary<MagickColor, int> dict = image.Histogram();

	var keyOfMaxValue = dict.Aggregate((x, y) => x.Value > y.Value ? x : y).Key;

	System.Drawing.Color c = keyOfMaxValue.ToColor();
	ssdominantColourCode = "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}
Cheers