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

时间:2012-08-10 20:25:13

标签: c# algorithm image-processing bitmap 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);
                }
            }
        }

当我运行我的代码和输入时出现问题 Before 我明白了 After

我想要的是 Want

如果您在我的代码中发现问题,请了解更好的算法,或者以某种方式设法完成,只需告诉我。先谢谢你们!

1 个答案:

答案 0 :(得分:4)

问题:

您正在将背景颜色更改为非背景颜色,然后通过后续像素检查进行拾取。

解决方案:

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