gpt4 book ai didi

.net - .NET检测灰度图像

转载 作者:行者123 更新时间:2023-12-04 03:00:01 24 4
gpt4 key购买 nike

我正在将文档扫描为JPG图像。扫描仪必须将所有页面扫描为彩色页面或将所有页面扫描为黑白页面。由于我的许多页面都是彩色的,因此我必须将所有页面扫描为彩色。扫描完成后,我想使用.Net检查图像,并尝试检测黑白图像,以便将这些图像转换为灰度图像并保存在存储中。

有人知道如何使用.Net检测灰度图像吗?

请告诉我。

最佳答案

一种测试颜色的简单算法:在嵌套的for循环(宽度和高度)中逐像素遍历图像,并测试像素的RGB值是否相等。如果不是,则图像具有颜色信息。如果您在所有像素中都做到了这一点,而又没有遇到这种情况,那么您将获得一个灰度图像。

使用更复杂的算法进行修订:

在这篇文章的第一版中,我提出了一种简单的算法,该算法假定如果每个像素的RGB值相等,则像素为灰度。因此0,0,0或128,128,128或230,230,230的RGB都将测试为灰色,而123,90,78则不会。简单的。

这是一段代码,用于测试与灰色之间的差异。这两种方法只是更复杂过程的一小部分,但应提供足够的原始代码来帮助解决原始问题。

/// <summary>
/// This function accepts a bitmap and then performs a delta
/// comparison on all the pixels to find the highest delta
/// color in the image. This calculation only works for images
/// which have a field of similar color and some grayscale or
/// near-grayscale outlines. The result ought to be that the
/// calculated color is a sample of the "field". From this we
/// can infer which color in the image actualy represents a
/// contiguous field in which we're interested.
/// See the documentation of GetRgbDelta for more information.
/// </summary>
/// <param name="bmp">A bitmap for sampling</param>
/// <returns>The highest delta color</returns>
public static Color CalculateColorKey(Bitmap bmp)
{
Color keyColor = Color.Empty;
int highestRgbDelta = 0;

for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
if (GetRgbDelta(bmp.GetPixel(x, y)) <= highestRgbDelta) continue;

highestRgbDelta = GetRgbDelta(bmp.GetPixel(x, y));
keyColor = bmp.GetPixel(x, y);
}
}

return keyColor;
}

/// <summary>
/// Utility method that encapsulates the RGB Delta calculation:
/// delta = abs(R-G) + abs(G-B) + abs(B-R)
/// So, between the color RGB(50,100,50) and RGB(128,128,128)
/// The first would be the higher delta with a value of 100 as compared
/// to the secong color which, being grayscale, would have a delta of 0
/// </summary>
/// <param name="color">The color for which to calculate the delta</param>
/// <returns>An integer in the range 0 to 510 indicating the difference
/// in the RGB values that comprise the color</returns>
private static int GetRgbDelta(Color color)
{
return
Math.Abs(color.R - color.G) +
Math.Abs(color.G - color.B) +
Math.Abs(color.B - color.R);
}

关于.net - .NET检测灰度图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1877405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com