How can I using code in C# for color extraction?

妖精的绣舞 提交于 2019-12-11 08:27:07

问题


I need help to extract specified color (red for example) from an image then cropping objects which contain this color.

This part is so important in my graduate project which tracking laser gesture in projector screen.


回答1:


I'm really not sure I understood you correctly, but here is a code that makes only red parts of an image visible.

You can change it to only red parts invisible by changing > to < when comparing to 200. You can also play with the number 200 to see what threshold is good for your is-red check.

private static unsafe void OnlyRed(Bitmap bitmap, Color replacement)
{
    var redOffset = 0;
    var bpp = 32;
    var bytesRep = new List<byte> {replacement.R, replacement.G, replacement.B};

    switch (bitmap.PixelFormat)
    {
        case PixelFormat.Format24bppRgb:
            bpp = 24;
            break;
        case PixelFormat.Format32bppArgb:
            redOffset = 8;
            bytesRep.Insert(0, replacement.A);
            break;
        case PixelFormat.Format32bppRgb:
        case PixelFormat.Canonical:
            bytesRep.Add(replacement.A);
            break;
        default:
            throw new NotSupportedException("Pixel format unsupported.");
    }

    var data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                               ImageLockMode.ReadWrite,
                               bitmap.PixelFormat);

    var start = (byte*)data.Scan0;
    var end = start + data.Height * data.Stride;

    for (var curr = start; curr < end; curr += bpp / 8)
    {
        if (curr[redOffset] > 200)
        {
            continue;
        }

        for (var i = 0; i < bytesRep.Count; i++)
        {
            curr[i] = bytesRep[i];
        }
    }

    bitmap.UnlockBits(data);
}

Usage:

var bitmap = new Bitmap("file location...");
OnlyRed(bitmap, Color.Transparent);


来源:https://stackoverflow.com/questions/10257831/how-can-i-using-code-in-c-sharp-for-color-extraction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!