如何获得像素表面积(二进制图像)?

时间:2016-06-23 11:55:46

标签: c# image-processing

我需要获得构成单个气泡的像素数。

enter image description here

我试过了一个洪水填充方法:点击"白色"泡沫区域并填充黑色 以及白色像素的所有更改的摘要。 但问题是内部黑色区域的出现,如下enter image description here

有任何想法吗?

这是我的FloodFill方式:

   public void FloodFill(int x, int y, Color new_color)
    {
        // Make sure the bitmap is locked.
        if (!IsLocked)
            throw new InvalidOperationException(
                "Bitmap32 object must be locked before you call FloodFill");

        // Get the old and new colors' components.
        byte old_r, old_g, old_b, old_a;
        GetPixel(x, y, out old_r, out old_g, out old_b, out old_a);
        byte new_r = new_color.R;
        byte new_g = new_color.G;
        byte new_b = new_color.B;
        byte new_a = new_color.A;

        // If the colors are the same, we're done.
        if ((old_r == new_r) && (old_g == new_g) &&
            (old_b == new_b) && (old_a == new_a)) return;

        // Start with the original point in the stack.
        Stack<Point> points = new Stack<Point>();
        points.Push(new Point(x, y));
        SetPixel(x, y, new_r, new_g, new_b, new_a);

        // While the stack is not empty, process a point.
        while (points.Count > 0)
        {
            Point pt = points.Pop();
            if (pt.X > 0) CheckPoint(points, pt.X - 1, pt.Y, old_r, old_g, old_b, old_a, new_r, new_g, new_b, new_a);
            if (pt.Y > 0) CheckPoint(points, pt.X, pt.Y - 1, old_r, old_g, old_b, old_a, new_r, new_g, new_b, new_a);
            if (pt.X < Width - 1) CheckPoint(points, pt.X + 1, pt.Y, old_r, old_g, old_b, old_a, new_r, new_g, new_b, new_a);
            if (pt.Y < Height - 1) CheckPoint(points, pt.X, pt.Y + 1, old_r, old_g, old_b, old_a, new_r, new_g, new_b, new_a);
        }
    }

    // See if this point should be added to the stack.
    private void CheckPoint(Stack<Point> points, int x, int y, byte old_r, byte old_g, byte old_b, byte old_a, byte new_r, byte new_g, byte new_b, byte new_a)
    {
        // See if the pixel at this point matches the old color.
        byte r, g, b, a;
        GetPixel(x, y, out r, out g, out b, out a);
        if ((r == old_r) && (g == old_g) && (b == old_b) && (a == old_a))
        {
            // It matches. Push it and color it.
            points.Push(new Point(x, y));
            SetPixel(x, y, new_r, new_g, new_b, new_a);
            PixelsNumber++;
        }
    }

0 个答案:

没有答案