我正在尝试通过获取所有像素并将其保存在颜色
列表中来计算给定图像的最佳调色板(对于 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
GroupBy
和 OrderByDescending
对查询进行分组和排序结果,然后使用 FirstOrDefault
或 First
只获取组中的第一个元素:
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/