连通域标记代码
时间: 2023-07-02 16:07:52 浏览: 52
以下是连通域标记的 Python 代码示例:
```python
import numpy as np
def label_connected_regions(image):
"""
连通域标记算法,对二值图像进行标记并返回标记结果
"""
# 定义连通域标记矩阵
labeled = np.zeros(image.shape, dtype=int)
# 定义当前标记
current_label = 1
# 遍历二值图像的每一个像素
for i in range(image.shape[0]):
for j in range(image.shape[1]):
# 如果当前像素为前景色且未被标记
if image[i,j] == 1 and labeled[i,j] == 0:
# 以当前像素为种子点进行扩展
current_label += 1
stack = [(i,j)]
while stack:
x,y = stack.pop()
labeled[x,y] = current_label
# 扩展上下左右四个方向的像素
if x > 0 and image[x-1,y] == 1 and labeled[x-1,y] == 0:
stack.append((x-1,y))
if x < image.shape[0]-1 and image[x+1,y] == 1 and labeled[x+1,y] == 0:
stack.append((x+1,y))
if y > 0 and image[x,y-1] == 1 and labeled[x,y-1] == 0:
stack.append((x,y-1))
if y < image.shape[1]-1 and image[x,y+1] == 1 and labeled[x,y+1] == 0:
stack.append((x,y+1))
return labeled
```
其中,`image` 是一个二值图像,前景色为 1,背景色为 0。函数返回一个与 `image` 相同大小的矩阵,其中每个前景像素被标记为一个正整数,表示它属于哪一个连通域。