1.5.12.12. 演示连接组件

在二维数组中提取和标记连接组件

import numpy as np
import matplotlib.pyplot as plt

生成一些二进制数据

x, y = np.indices((100, 100))
sig = (
np.sin(2 * np.pi * x / 50.0)
* np.sin(2 * np.pi * y / 50.0)
* (1 + x * y / 50.0**2) ** 2
)
mask = sig > 1
plt.figure(figsize=(7, 3.5))
plt.subplot(1, 2, 1)
plt.imshow(sig)
plt.axis("off")
plt.title("sig")
plt.subplot(1, 2, 2)
plt.imshow(mask, cmap="gray")
plt.axis("off")
plt.title("mask")
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)
sig, mask

标记连接组件

import scipy as sp
labels, nb = sp.ndimage.label(mask)
plt.figure(figsize=(3.5, 3.5))
plt.imshow(labels)
plt.title("label")
plt.axis("off")
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)
label

提取第 4 个连接组件,并在其周围裁剪数组

sl = sp.ndimage.find_objects(labels == 4)
plt.figure(figsize=(3.5, 3.5))
plt.imshow(sig[sl[0]])
plt.title("Cropped connected component")
plt.axis("off")
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)
plt.show()
Cropped connected component

脚本总运行时间:(0 分钟 0.110 秒)

由 Sphinx-Gallery 生成的图库