如果我知道背景颜色,如何创建图像轮廓?

Bos*_*sak 7 c# algorithm bitmap image-processing outline

我想创建一个简单的程序,打开任何给定的图像,并选择2种颜色:BackgroundColorOutlineColor.然后围绕"对象"做一个轮廓.

到目前为止,这是我的代码:

        for (int y = 1; y < height - 1; y++) //iterate trough every pixel 
        {                                    //in my bitmap
            for (int x = 1; x < width - 1; x++)
            {
                //i want to put a pixel only if the the curent pixel is background
                if (bitmap.GetPixel(x, y) != BackgroundColor)
                    continue;

                var right = bitmap.GetPixel(x + 1, y);
                var down = bitmap.GetPixel(x, y + 1);
                var up = bitmap.GetPixel(x, y - 1);
                var left = bitmap.GetPixel(x - 1, y);
                //get the nearby pixels
                var neibours = new List<Color> {up, down, left, right};

                var nonBackgroundPix = 0;
                //then count how many are not outline nor background color
                foreach (Color neibour in neibours)
                {
                    if (neibour != BackgroundColor && neibour != OutlineColor)
                    {
                        nonBackgroundPix++;
                    }
                }
                //finaly put an outline pixel only if there are 1,2 or 3 non bg pixels
                if (nonBackgroundPix > 0 && nonBackgroundPix < 4)
                {
                    bitmap.SetPixel(x, y, OutlineColor);
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

当我运行我的代码和输入时,问题出现了 之前 我明白了 后

而我想要的是 想

如果您在我的代码中发现问题,请知道更好的算法,或者以某种方式设法做到这一点告诉我.先谢谢你们!

The*_*heZ 4

问题:

您正在将背景颜色更改为非背景颜色,然后由后续像素检查拾取该非背景颜色。

解决方案:

我建议存储一个新的数组,其中包含“稍后更改”的像素,然后在映射完整图像后返回并设置它们。(此外,您可以立即更改它,然后向您可以检查的像素添加一个标志,但这是您需要实现的更多逻辑,例如检查布尔数组)