改进一种算法来定位由0和1的二维矩阵表示的对象的极值



注意:这里不是在寻找代码,只是一个算法,因为我不想实现这个问题的解决方案,而是想找出解决方案。

我有一个大的二维数组,我从一个由零和一组成的图像中创建;这些表示黑色像素,反之亦然。背景为白色,图片中包含许多形状不规则的黑色物体。我已经写了检测这些物体边缘的代码,所以假设这个二维阵列只包含这些物体的边缘,因为处理步骤已经完成

我正在尝试创建一种算法,能够为每个对象找到四个极值:最高的y、最低的y、最大的x和最低的x。

我现在拥有的最好的伪代码是:

Initialize array = aforementioned array
Initialize temporary_coord_store=[]
Initialize coordinates=where value in array equals one
Initialize extrema=[]
Define coordinate_recurs(coordinates):
Initialize x = first value in coordinates
append x to temporary_coord_store
loop while the following if statement evaluates true:
if the value in array at an index equal to any neighbors of any coordinate in coordinates equals 1:
append all neighbors to temporary_coord_store
append to extrema the extreme x and y values in temporary coordinate store
set all values in array at indexes equal to any values in temporary coordinate store=zero
set coordinates=where value in array equals one
if any value in coordinates equals one:
call method coordinate_recurs(coordinates)
call method coordinate_recurs(coordinates)

然而,我觉得必须有一个更高效的算法可以设计出来,因为这基本上是针对所有非白色数组值的。有人看到我可以用这个伪代码节省一些时间的地方了吗?如果这是张贴在错误的渠道堆栈交换道歉;如果是,请告诉我,这样我就可以把它放在正确的地方。

当您访问邻居时,您可以调整标准的连接组件标记算法,只需考虑在适当的方向上扩展当前极值。例如,如果您在东部找到当前单元格的邻居,则只需考虑增加最大x值。

为了简化,我假设你的边界是4连通的。我也忽略了确定邻居是否有效的问题,即在图像内。

image[][]   // array containing 0|1
visited[][] // boolean
queue[]     // struct to hold coordinates to be processed
extrema[]   // array of object extrema
id = 0      // current object id
for y = 0 to image.height-1
for x = 0 to image.width-1
if image[x][y] == 1 and visited[x][y] == false
// new object/component
id = id + 1
extrema[id] = (x,y)
queue.add(x,y)
visited[x][y] = true
while queue not empty
p = queue.remove()
// Check East
if image[x+1][y] == 1 and visited[x+1][y] == false
queue.add(p.x+1, p.y)
visited[p.x+1][p.y] = true
if x+1 > extrema[id].maxX 
extrema[id].maxX = x+1
// Consider North, South, West...

最新更新