获取PNG中最常用的颜色

发布于 2024-10-10 05:25:48 字数 60 浏览 0 评论 0原文

我需要使用 C# 获取 png 图像文件中最常见的颜色。这样我就可以绘制一些与图像中包含的颜色相似的文本。

I need to obtain the most common color in a png image file using c#. This is so I can draw some text with similar colors contained within the image.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

嘦怹 2024-10-17 05:25:48

您可以使用颜色直方图,将 RGB 或 HSV(取决于您的颜色空间)值采样到类别。但是,如果您希望通过实际值识别大部分颜色,则必须单独计算每种颜色的出现次数。

You can use a colour histogram, sampling the RGB or HSV (depending on your colour space) values into categories. However, if you want the mostly colour identified by actual values, you'll have to count the occurance of each colour seperately.

哆兒滾 2024-10-17 05:25:48

也许有一些库可以为您做到这一点,但如果没有,我想您可以循环遍历所有像素,根据出现的次数制作您找到的所有颜色的地图,最后得到最常用的颜色。

Maybe there are some libraries that will do it for you, but if not, I guess you can just cycle through all pixels, make a map of all colours you find with the number of occurances and in the end get the one that's most used.

迷雾森÷林ヴ 2024-10-17 05:25:48

如果您正在查看实际的像素值,我会使用排序字典:

SortedDictionary

并循环遍历所有像素。如果您不知道如何循环遍历像素,请查看 Bitmap.LockBits< /a>.就您的目的而言,GetPixel 太慢了。

编辑:

我对排序不是 100% 确定。我同意 CodeInChaos - 无论如何,直接的字典可能会更快。然后,您必须对字典进行一次循环才能获得最常见的值。

If you're looking at the actual pixel values, I'd use a sorted dictionary:

SortedDictionary<Color,int>

and loop through all the pixels. If you don't know how to loop through the pixels, check out Bitmap.LockBits. For your purposes, GetPixel would be way too slow.

Edit:

I'm not 100% sure about the sorting. I agree with CodeInChaos - a straight dictionary is likely to be faster anyways. You'll have to then do a single loop through the dictionary to get your most common value.

万劫不复 2024-10-17 05:25:48

可以使用直方图算法来计算每种颜色,但这可能不是您想要的。极其相似的颜色应该放在一起计算。

我建议使用八叉树颜色量化,它会在计数时自动减少颜色数量,从而将相似的颜色分组到一个存储桶中。该算法的一种描述:http://www.cubic.org/docs/octree.htm

忘记提及:此建议仅适用于 24 位 PNG。对于 8 位 PNG,您已经有了一个可以进行颜色分组的调色板。只需要构建一个 256 值表并在遇到每个调色板索引时对其进行计数。

Counting each color can be done with a histogram algorithm, but that's probably not what you're looking for. Colors that are extremely similar should be counted together.

I would suggest using an Octree Color Quantization, which will automatically reduce the number of colors as it counts thereby grouping similar colors into a single bucket. One description of the algorithm: http://www.cubic.org/docs/octree.htm

Forgot to mention: this advice is only for 24-bit PNG. For 8-bit PNG, you already have a palette that does the color grouping. It's only necessary to build a 256 value table and keep a count of each palette index as you encounter it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文