c#.NET绿屏背景删除

use*_*381 4 c# wpf image-manipulation chromakey

我正在研究适用于Windows 8的台式电脑照片软件.我希望能够通过色度键控从照片中删除绿色背景.

我是图像处理的初学者,我找到了一些很酷的链接(比如http://www.quasimondo.com/archives/000615.php),但我不能用c#代码转换它.

我正在使用网络摄像头(使用aforge.net)查看预览并拍照.我尝试过滤色镜,但绿色背景并不是很均匀,所以这不起作用.

如何在C#中正确地做到这一点?

Mar*_*rio 7

它会起作用,即使背景不均匀,你也只需要适当的策略来攫取你所有的绿屏而不更换任何其他内容.

由于链接页面上至少有一些链接已经死亡,我尝试了自己的方法:

  • 基础知识很简单:将图像像素的颜色与某个参考值进行比较,或应用其他一些公式来确定它是否应该透明/替换.

  • 最基本的公式将涉及"确定绿色是否是最大价值"这样简单的事情.虽然这适用于非常基本的场景,但它可以搞砸你(例如白色或灰色也会被过滤).

我使用一些简单的示例代码玩弄了一下.当我使用Windows Forms时,它应该是可移植的而没有问题,我很确定你能够解释代码.请注意,这不一定是执行此操作的最佳方式.

Bitmap input = new Bitmap(@"G:\Greenbox.jpg");

Bitmap output = new Bitmap(input.Width, input.Height);

// Iterate over all piels from top to bottom...
for (int y = 0; y < output.Height; y++)
{
    // ...and from left to right
    for (int x = 0; x < output.Width; x++)
    {
        // Determine the pixel color
        Color camColor = input.GetPixel(x, y);

        // Every component (red, green, and blue) can have a value from 0 to 255, so determine the extremes
        byte max = Math.Max(Math.Max(camColor.R, camColor.G), camColor.B);
        byte min = Math.Min(Math.Min(camColor.R, camColor.G), camColor.B);

        // Should the pixel be masked/replaced?
        bool replace =
            camColor.G != min // green is not the smallest value
            && (camColor.G == max // green is the biggest value
            || max - camColor.G < 8) // or at least almost the biggest value
            && (max - min) > 96; // minimum difference between smallest/biggest value (avoid grays)

        if (replace)
            camColor = Color.Magenta;

        // Set the output pixel
        output.SetPixel(x, y, camColor);
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用了维基百科示例图像,得到了以下结果:

蒙面结果(洋红色将被你的背景取代)

不过请注意,你可能需要不同的阈值(896上面我的代码),你甚至可能要使用不同的术语,以确定一些像素是否要进行更换.您还可以在帧之间添加平滑,混合(绿色差异较小)等,以减少硬边缘.