泛型填充二进制图像的C ++算法 [英] C++ algorithm for flood filling a binary image

查看:199
本文介绍了泛型填充二进制图像的C ++算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图模拟一个matlab函数imfill用于洪水填充二进制图像(1和零的2D矩阵)。

I am trying to simulate a matlab function "imfill" for flood filling a binary image (2D matrix of 1's and zeros).

我想指定一个开始点在矩阵中,和像imfill的4连接版本一样的洪水填充将做。

I want to specify a starting point in the matrix, and flood fill like a 4 connected version of imfill would do.

这在C ++世界的某个地方已经存在吗?

Does this already exist out there somewhere in the C++ world? If not, what would be the most efficient way to implement this?

推荐答案

如果你的图片只是1和0的二维数组,然后我不认为你需要一个实际的图形库。

If your images are just 2D arrays of 1s and 0s, then I don't think you need an actual graphics library.

当我填写简单的网格过去,我只是使用STL队列存储点列表,然后通过那些工作。队列将从初始点开始,然后我将测试相邻点。如果相邻点需要包括在flood中,那么将它们添加到队列中。类似这样:

When I've filled in simple grids in the past, I just used the STL queue to store a list of points, and then worked through those. The queue would start with the initial point, then I'd test the adjacent points. If the adjacent points need to be included in the 'flood', then add those to the queue. Kind of like this:

// using this data structure
struct Point {
  int x;
  int y;
};

// 
void fillGrid(Point orig, byte** grid, int width, int height) {
  std::queue<Point> q;
  q.push(orig);

  // the main flood loop
  while(!q.empty()) {
    Point pnt = q.front();
    q.pop();

    // grab adjacent points
    Point adj[4];
    adj[0].x = pnt.x;   adj[0].y = pnt.y-1;   // up
    adj[1].x = pnt.x+1; adj[1].y = pnt.y;     // right
    adj[2].x = pnt.x;   adj[2].y = pnt.y+1;   // down
    adj[3].x = pnt.x-1; adj[3].y = pnt.y;     // left

    for(int i = 0; i < 4; i++) {
      // don't forget boundaries!
      if(adj[i].x < 0 || adj[i].x >= width ||
         adj[i].y < 0 || adj[i].y >= height)
        continue;

      // if adjacent point meets some criteria, then set
      // its value and include it in the queue
      if(includePoint(adj[i], grid)) {
        setPoint(adj[i], grid);
        q.push(adj[i]);
      }
    }
  }
}

这篇关于泛型填充二进制图像的C ++算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆