二值化图像找连通区域python
时间: 2023-09-05 17:13:32 浏览: 180
有多种方法可以实现二值化图像找连通区域,下面是其中一种基于深度优先搜索的 Python 实现:
```python
import numpy as np
def find_connected_components(image):
# 获取图像大小
height, width = image.shape[:2]
# 创建一个与图像大小相同的标记数组,用于记录已经访问过的像素
visited = np.zeros((height, width))
# 连通区域列表
connected_components = []
# 遍历整个图像
for i in range(height):
for j in range(width):
# 如果当前像素已经访问过,跳过
if visited[i][j]:
continue
# 如果当前像素为白色,跳过
if image[i][j] == 255:
continue
# 否则,当前像素为黑色,是一个新的连通区域的起点
# 创建一个新的连通区域,并添加起点
connected_component = []
connected_component.append((i, j))
# 标记当前像素已经访问过
visited[i][j] = 1
# 深度优先搜索,找到所有连通的黑色像素
stack = [(i, j)]
while stack:
current_i, current_j = stack.pop()
# 检查当前像素的上下左右四个方向
for di, dj in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
neighbor_i, neighbor_j = current_i + di, current_j + dj
# 如果邻居像素超出图像边界,跳过
if neighbor_i < 0 or neighbor_i >= height or neighbor_j < 0 or neighbor_j >= width:
continue
# 如果邻居像素已经访问过,跳过
if visited[neighbor_i][neighbor_j]:
continue
# 如果邻居像素为白色,跳过
if image[neighbor_i][neighbor_j] == 255:
continue
# 否则,邻居像素为黑色,加入当前连通区域,并标记已访问
connected_component.append((neighbor_i, neighbor_j))
visited[neighbor_i][neighbor_j] = 1
stack.append((neighbor_i, neighbor_j))
# 将当前连通区域加入列表
connected_components.append(connected_component)
return connected_components
```
使用方法:
```python
import cv2
# 读入图像并二值化
image = cv2.imread('image.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 找到连通区域
connected_components = find_connected_components(binary)
# 输出连通区域数量
print(len(connected_components))
```
阅读全文