2012-07-29 82 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); 
    } 
} 
相關問題