本文要点在于Python扩展库numpy、scipy、matplotlib的用法和数学形态学中开、闭、腐蚀、膨胀等运算的实现。
>>> import numpy as np
>>> from scipy import ndimage
>>> import matplotlib.pyplot as plt
>>> square = np.zeros((32,32)) #全0数组
>>> square[10:20, 10:20] = 1 #把其中一部分设置为1
>>> x, y = (32*np.random.random((2, 15))).astype(np.int) #随机位置
>>> square[x,y] = 1 #把随机位置设置为1
>>> plt.imshow(square) #显示原始随机图像
>>> plt.show()
>>> open_square = ndimage.binary_opening(square) #开运算
>>> plt.imshow(open_square) #开运算结果
>>> plt.show()
>>> closed_square = ndimage.binary_closing(square) #闭运算
>>> plt.imshow(closed_square) #显示闭运算结果
>>> plt.show()
>>> eroded_square = ndimage.binary_erosion(square) #腐蚀运算
>>> plt.imshow(eroded_square)
>>> plt.show()
>>> dilation_square = ndimage.binary_dilation(square) #膨胀运算
>>> plt.imshow(dilation_square)
>>> plt.show()