img=cv2.imread('dige.png',0)
kernel = np.ones((3,3),np.uint8)
num=[[]]*6
for i in range(6):
num[i] = cv2.erode(img,kernel,iterations = i)
plt_show(num[0],num[1],num[2],num[3],num[4],num[5])
可看出腐蚀操作使得线条变细直至消失
img=cv2.imread('dige.png',0)
kernel = np.ones((3,3),np.uint8)
num=[[]]*6
for i in range(6):
num[i] = cv2.dilate(img,kernel,iterations = i)
plt_show(num[0],num[1],num[2],num[3],num[4],num[5])
可看出线条不断变粗
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
plt_show(img,opening,closing)
β ( A ) = A − ( A ⊖ B ) \beta\left(A\right) =A-\left(A\ominus B\right) β(A)=A−(A⊖B)
# 原图-腐蚀
a=cv2.imread('am.png',0)
kernel = np.ones((3,3),np.uint8)
a2=cv2.erode(a,kernel,iterations = 1)
plt_show(a,a2,a-a2)
形态学梯度:膨胀-腐蚀
img=cv2.imread('am.png',0)
kernel = np.ones((3,3),np.uint8)
dilate = cv2.dilate(img,kernel,iterations = 1)
erosion = cv2.erode(img,kernel,iterations = 1)
img2=dilate-erosion
plt_show(img,dilate,erosion,img2)
上图中,(膨胀-腐蚀)可得出梯度(最后一幅图)
礼帽与黑帽
img = cv2.imread('dige.png')
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, np.ones((7,7),np.uint8) )
blackhat = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT, np.ones((15,15),np.uint8) )
plt_show(img,tophat,blackhat)