摩尔领域也称为8邻域或者间接邻域。
摩尔邻域跟踪算法的基本思想:
边界追踪:
Moore’s 算法 The general idea is:
• every time you hit a black pixel, P, backtrack i.e. go back to the white pixel you were previously standing on, then,
• go around pixel P in a clockwise direction, visiting each pixel in its Moore neighborhood, until you hit a black pixel.
• The algorithm terminates when the start pixel is visited for a second time.
中文翻译:
-
找到一个黑色像素,并将它定为你的起始像素。(定位一个起始像素可以以多种方式来完成的;我们将从网格的左下角开始,自下而上扫描每一列像素,从最左向右的每列像素,直到遇到一个黑色的像素,我们将其作为我们的起始像素)。
-
每次遇到黑色像素,将设置为当前边界像素点
-
然后原路返回到先前到达的白色像素,以顺时针方向搜索的摩尔邻域内的每一个像素,直到遇到下一个黑色像素。
-
重复这个过程,当起始像素被第二次访问时算法终止,在整个运行过程走过的黒色像素就是目标的边界像素。
def Moore_Function(img):
trace = []
start_x = 0
start_y = 0
done = False
img_h, img_w = img.shape
for h in range(img_h - 2):
if done == True:
break
for w in range(img_w - 2):
if img[h, w] == 0:
start_x = w
start_y = h
done = True
break
#print("Start Point (%d %d)" % (start_x, start_y))
trace.append([start_x, start_y])
# 8邻域 顺时针方向搜索
neighbor = [[-1, -1], [0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0]]
neighbor_len = len(neighbor)
cur_x = start_x
cur_y = start_y
neig_idx = 7
while True:
for k in range(neighbor_len):
neig_k = (neig_idx + k) % neighbor_len
x = cur_x + neighbor[neig_k][0]
y = cur_y + neighbor[neig_k][1]
if (img[y, x] == 0):
trace.append([x, y])
cur_x = x
cur_y = y
neig_idx = neig_k - 1
break
if neig_idx < 0:
neig_idx += neighbor_len
if (cur_x == start_x) and (cur_y == start_y):
break
return trace