I am trying to quantize an image into 10 colors in C# and I have a problem in draw the quantized image, I have made the mapping table and it is correct, I have made a copy of the original image and I am changing the color of pixels based on the mapping table , I am using the below code:
bm = new Bitmap(pictureBox1.Image);
Dictionary<Color, int> histo = new Dictionary<Color, int>();
for (int x = 0; x < bm.Size.Width; x++)
for (int y = 0; y < bm.Size.Height; y++)
{
Color c = bm.GetPixel(x, y);
if (histo.ContainsKey(c))
histo[c] = histo[c] + 1;
else
histo.Add(c, 1);
}
var result1 = histo.OrderByDescending(a => a.Value);
int ind = 0;
List<Color> mostusedcolor = new List<Color>();
foreach (var entry in result1)
{
if (ind < 10)
{
mostusedcolor.Add(entry.Key);
ind++;
}
else
break;
}
Double temp_red,temp_green,temp_blue,temp;
Dictionary<Color, Double> dist = new Dictionary<Color, double>();
Dictionary<Color, Color> mapping = new Dictionary<Color, Color>();
foreach (var p in result1)
{
dist.Clear();
foreach (Color pp in mostusedcolor)
{
temp_red = Math.Pow((Convert.ToDouble(p.Key.R) - Convert.ToDouble(pp.R)), 2.0);
temp_green = Math.Pow((Convert.ToDouble(p.Key.G) - Convert.ToDouble(pp.G)), 2.0);
temp_blue = Math.Pow((Convert.ToDouble(p.Key.B) - Convert.ToDouble(pp.B)), 2.0);
temp = Math.Sqrt((temp_red + temp_green + temp_blue));
dist.Add(pp, temp);
}
var min = dist.OrderBy(k=>k.Value).FirstOrDefault();
mapping.Add(p.Key, min.Key);
}
Bitmap copy = new Bitmap(bm);
for (int x = 0; x < copy.Size.Width; x++)
for (int y = 0; y < copy.Size.Height; y++)
{
Color c = copy.GetPixel(x, y);
Boolean flag = false;
foreach (var entry3 in mapping)
{
if (c.R == entry3.Key.R && c.G == entry3.Key.G && c.B == entry3.Key.B)
{
copy.SetPixel(x, y, entry3.Value);
flag = true;
}
if (flag == true)
break;
}
}
pictureBox2.Image=copy;