连通区域标记算法代码python
时间: 2023-10-05 17:08:01 浏览: 150
连通区域标记算法的Python代码如下:
```python
import numpy as np
def labeling(image):
height, width = image.shape
labels = np.zeros_like(image)
current_label = 1
equivalences = {}
def find_root(label):
root = label
while equivalences[root != root:
root = equivalences[root]
return root
for y in range(height):
for x in range(width):
if image[y, x == 0:
continue
neighbors = []
if y > 0 and image[y-1, x == 1:
neighbors.append(labels[y-1, x])
if x > 0 and image[y, x-1 == 1:
neighbors.append(labels[y, x-1])
if len(neighbors) == 0:
labels[y, x = current_label
equivalences[current_label = current_label
current_label += 1
else:
root = min(neighbors)
labels[y, x = root
for neighbor in neighbors:
if neighbor != root:
equivalences = root
for y in range(height):
for x in range(width):
if image[y, x == 0:
continue
labels[y, x = find_root(labels[y, x])
unique_labels = np.unique(labels)
for i, label in enumerate(unique_labels):
equivalences[label = i
final_labels = np.zeros_like(labels)
for y in range(height):
for x in range(width):
if image[y, x == 0:
continue
final_labels[y, x = equivalences
阅读全文