[英]Get Dominant Color from Image in UWP C#
Basically I have a UWP app that allows user to open image files (.jpg, .jpeg, .png) and I need to detect the dominant color from that image.基本上我有一个 UWP 应用程序,它允许用户打开图像文件(.jpg、.jpeg、.png),我需要从该图像中检测主色。
I found solutions with GDI+ using System.Drawing but That's not available in UWP. I couldn't find any reference of similar thing in Win2D.我使用 System.Drawing 找到了 GDI+ 的解决方案,但在 UWP 中不可用。我在 Win2D 中找不到类似内容的任何参考。 So is there a way to get the dominant color from Histogram?那么有没有办法从直方图中获取主色呢?
I can always use any Web Service and get this done with python or node.js etc but I want to do it natively inside the UWP app without the requirement of inte.net.我可以随时使用任何 Web 服务并通过 python 或 node.js 等完成此操作,但我想在 UWP 应用程序内本地完成,而不需要 inte.net。
Any Help Appreciated !任何帮助表示赞赏!
We did it in the following way: 我们通过以下方式做到了:
For each pixel: Convert to HSL. 对于每个像素:转换为HSL。 Use H and S to determine the color. 使用H和S确定颜色。 Use L to determine the intensity. 使用L确定强度。 Sum all up a in a 2D matrix indexed by H and S. 在由H和S索引的2D矩阵中对a求和。
Find the largest value in the matrix. 在矩阵中找到最大值。 That is your dominant color. 那是你的主导色彩。
Take a look at this repo: ColorThief and its Nuget package . 看看这个仓库 : ColorThief及其Nuget包 。 It has support for UWP. 它支持UWP。 You can also check this answer for more info. 您也可以查看此答案以获取更多信息。
UWP Works revise the code above UWP Works 修改上面的代码
//ksemenenko.ColorThief Nuget
async Task<SolidColorBrush> GetIdealTextColor(StorageFile file)
{
var solid = new SolidColorBrush();
solid = TextBlockHelper._textBrush;
var random = RandomAccessStreamReference.CreateFromFile(file);
using (IRandomAccessStream randomAccessStream = await random.OpenReadAsync())
{
var decoder = await BitmapDecoder.CreateAsync(randomAccessStream);
var colorThief = new ColorThiefDotNet.ColorThief();
var quantizedColor = await colorThief.GetColor(decoder);
solid = IdealTextColor(quantizedColor.Color);
}
return solid;
}
public SolidColorBrush IdealTextColor(ColorThiefDotNet.Color bg)
{
int nThreshold = 105;
int bgDelta = Convert.ToInt32((bg.R * 0.299) + (bg.G * 0.587) +
(bg.B * 0.114));
var foreColor = (255 - bgDelta < nThreshold) ? new SolidColorBrush(Colors.Black) : new SolidColorBrush(Colors.White);
return foreColor;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.