2012-07-29 83 views
2

我需要一个方向来执行此操作。我遍历所有像素并通过getpixel函数获取值。接下来我应该做什么?如何从图像中获得最常用的rgb颜色?

+1

[什么都有你试过](http://whathaveyoutried.com)?你有什么方法考虑?堆栈溢出不是一个能够帮助您思考或为您工作的地方 - 请向我们展示您已经完成的工作,并解释您卡在哪里。 – Oded 2012-07-29 20:25:53

回答

2

将它们汇总在Dictionary<Color, int>中,您可以在其中保留每种颜色的计数。在对所有这些进行迭代之后,提取Value(count)排序的前5个。

一个不太顺利执行,但简单的解决方法是这样的:

(from c in allColors 
group c by c into g 
order by g.Count() descending 
select g.Key).Take(5) 
1

我不会写代码的你,但给你所需要的一般描述:

  1. 一种数据结构,保存每种颜色及其出现的次数
  2. 对于每个像素,如果颜色存在于您的数据结构中,则增加数字 2.a如果颜色不存在,请将其添加1计数
  3. 一旦你通过所有像素了,排序的计数结构,并获得前5
0

创建这样一个字典:

Dictionary<Color, int> dictColors = new Dictionary<Color, int>(); 

那么当你通过每个像素迭代,为此

Color color =GetPixel(x,y); 
if(!dictColors.Contains(color)) 
{ 
dictColors.Add(color,0); 
} 
else 
{ 
dictColors[color]++; 
} 

then take first five: 
var top5 = dictColors.Take(5); 
+0

你有没有试过这段代码? – 2012-07-29 20:45:48

4

这里是一个辅助函数来获取所有像素:

public static IEnumerable<Color> GetPixels(Bitmap bitmap) 
{ 
    for (int x = 0; x < bitmap.Width; x++) 
    { 
     for (int y = 0; y < bitmap.Height; y++) 
     { 
      Color pixel = bitmap.GetPixel(x, y); 
      yield return pixel; 
     } 
    } 
} 

如果你只需要的颜色(不含计数器):

using (var bitmap = new Bitmap(@"...")) 
{ 
    var mostUsedColors = 
     GetPixels(bitmap) 
      .GroupBy(color => color) 
      .OrderByDescending(grp => grp.Count()) 
      .Select(grp => grp.Key) 
      .Take(5); 
    foreach (var color in mostUsedColors) 
    { 
     Console.WriteLine("Color {0}", color); 
    } 
} 

顺便说一句,这里是前5个最常用的颜色与柜台的选择:

using (var bitmap = new Bitmap(@"...")) 
{ 
    var colorsWithCount = 
     GetPixels(bitmap) 
      .GroupBy(color => color) 
      .Select(grp => 
       new 
        { 
         Color = grp.Key, 
         Count = grp.Count() 
        }) 
      .OrderByDescending(x => x.Count) 
      .Take(5); 

    foreach (var colorWithCount in colorsWithCount) 
    { 
     Console.WriteLine("Color {0}, count: {1}", 
      colorWithCount.Color, colorWithCount.Count); 
    } 
} 
相关问题