c# - 获取像素 + 按最常见的颜色排序

标签 c# wpf linq 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 种颜色。但我需要先按用途排序。我怎样才能做到这一点?

另外,你们还有其他方法吗?

最佳答案

如果您需要首先按使用情况(频率)排序,请考虑使用 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

关于c# - 获取像素 + 按最常见的颜色排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36288498/

相关文章:

c# - 根据数据网格中的行选择打开表单

c# - 如何使用 List<T>() 隐藏私有(private)字段?

C#WPF Textblock每行不同的字体颜色

wpf - DataTrigger.ExistActions 未针对绑定(bind)值 "null"触发

c# - LINQ 从第一个列表中选择

C# winforms如何在不同的事件处理程序中访问同一对象

c# - 如何启用 Visual Studio 2015 诊断工具 "Showing events for:"类别和线程筛选器

c# - Linq2Sql Designer 将存储过程多个结果集变为单个

c# - 在哪里存储 AES key ?

c# - 将条件表达式解析为字符串