内置函数:findContours().
例子:
import numpy as np
import matplotlib.pyplot as plt
a = np.zeros((100,100), np.uint8)
a[10:20,30:40] = 1
im2, contours, hierarchy = cv2.findContours(a, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cim = np.zeros_like(a)
cv2.drawContours(cim, contours, -1, 255, 1)
plt.matshow(cim, cmap=plt.cm.gray)
手动方法:一种简单的方法是使用binary_erosion() 从原始图像中减去eroded image。
这不一定会导致闭合轮廓,具体取决于几何形状。
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage.morphology import binary_erosion
a = np.zeros((100,100), np.uint8)
a[10:20,30:40] = 1
m = a - binary_erosion(a)
plt.matshow(m, cmap=plt.cm.gray)