在 C# 中确定位图中的像素是否为任何绿色阴影

wil*_*oup 2 c# pixel bitmap

我目前有以下代码来查看位图的像素:

public struct Pixel
{
    public byte Blue;
    public byte Green;
    public byte Red;
    public byte Alpha;

    public Pixel(byte blue, byte green, byte red, byte alpha)
    {
        Blue = blue;
        Green = green;
        Red = red;
        Alpha = alpha;
    }
}

    public unsafe void Change(ref Bitmap inputBitmap)
    {
        Rectangle imageSize = new Rectangle(0, 0, inputBitmap.Width, inputBitmap.Height);
        BitmapData imageData = inputBitmap.LockBits(imageSize, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

        for (int indexY = 0; indexY < imageData.Height; indexY++)
        {
            byte* imageDataBytes = (byte*)imageData.Scan0 + (indexY * imageData.Stride);

            for (int indexX = 0; indexX < imageData.Width; indexX++)
            {
                Pixel pixel = GetPixelColour(imageDataBytes, indexX);
            }
        }

        inputBitmap.UnlockBits(imageData);
    }
Run Code Online (Sandbox Code Playgroud)

一旦读取了字节中的像素,我希望能够确定该像素是否是绿色阴影。我在弄清楚应该用什么数学方法来确定特定阴影和绿色与所看到的阴影和绿色之间的距离时遇到一些问题。

预先感谢您的帮助。

Pho*_*cUK 5

其中纯绿色为 0,255,0 - 您需要做的是获取每个像素的 R、G 和 B 分量之间的差异并对它们进行平均。假设您有一个像素为 100,200,50(这是一个灰绿色: https: //www.colorcodehex.com/64c832/) - R、G 和 B 的平均值差异将为 100,55,50 68(这 3 个差异之和除以 3)。平均值越接近 0,它就越接近您的参考颜色。

然后你需要做的是选择一个“阈值”——允许你距离参考颜色多远,但仍然被认为足够接近,然后任何低于该阈值的东西都被视为绿色,然后你就可以做任何事情你喜欢它。