获取像素+ OrderBy最常用的颜色

时间:2016-03-29 15:22:42

标签: c# wpf linq colors

我尝试通过获取所有像素并保存在Colors列表中来计算给定图像的最佳调色板(对于gif,最多256种颜色)。

var bmp = new WriteableBitmap(bitmapSource);
bmp.Lock();

int stride = bmp.PixelWidth * 4;
int size = bmp.PixelHeight * stride;
var imgData = new byte[size];
//int index = y * stride + 4 * x; //To acess a specific pixel.

Marshal.Copy(bmp.BackBuffer, imgData, 0, imgData.Length);

bmp.Unlock();

var colorList = new List<Color>();

//I'm not sure if this is right.
for (int index = 0; index < imgData.Length - 1; index += 4)
{
    colorList.Add(Color.FromArgb(imgData[index], imgData[index + 1], 
                  imgData[index + 2], imgData[index + 3]));
}

//Here is the main problem.
var palette = colorList.Distinct().Take(255);

目前,我能够区分所有颜色,只采用前255个颜色。但我需要先按使用顺序排序。我怎么能这样做?

另外,你们有没有其他方法可以做到这一点?

1 个答案:

答案 0 :(得分:2)

如果您需要先按使用情况(频率)排序,请考虑使用LINQ GroupByOrderByDescending对查询结果进行分组和排序,然后只采用第一个元素使用FirstOrDefaultFirst

在群组中
var result = colorList
              .GroupBy<int, int>(x => x) //grouping based on its value
              .OrderByDescending(g => g.Count()) //order by most frequent values
              .Select(g => g.FirstOrDefault()) //take the first among the group
              .ToList(); //not necessarily put if you want to return IEnumerable