Pregunta

I want to create a simple program that you open any given image and select 2 colors: BackgroundColor and OutlineColor. Then make an outline around the "object".

Here is my code so far:

        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);
                }
            }
        }

And here comes the problem when I run my code and input Before I get After

And what I want is Want

If you find a problem in my code, know better algorithm for doing this or manage to do it in some way just tell me. Thanks in advance guys!

¿Fue útil?

Solución

The problem:

You are changing the background color into a non-background color which is then being picked up by subsequent pixel checks.

The solution:

I'd suggest storing a new array with pixels "to be changed later" and then once the full image is mapped go back and set those. (Also, you can change it immediately and then add a flag to the pixel you can check for, but this is more logic you'd need to implement such as checking against a boolean array)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top