import cv2
import numpy as np
#腐蚀
img = cv2.imread('str.jpg')
ret,binary = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
kernel_1 = np.ones((5,5),dtype=np.uint8)
erosion1 = cv2.erode(binary,kernel_1,iterations=1)
plt.subplot(121),plt.imshow(binary),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(erosion1),plt.title('Eroded1')
plt.xticks([]), plt.yticks([])
plt.show()
#膨胀
kernel_1 = np.ones((5,5),dtype=np.uint8)
dilation1 = cv2.dilate(binary,kernel_1,iterations=1)
plt.subplot(121),plt.imshow(binary),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(dilation1),plt.title('Dilated1')
plt.xticks([]), plt.yticks([])
plt.show()
## 开运算(先腐蚀,后膨胀)
opening = cv2.morphologyEx(binary2,cv2.MORPH_OPEN,kernel_1)
plt.subplot(121),plt.imshow(binary2),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(opening),plt.title('Open')
plt.xticks([]), plt.yticks([])
plt.show()
## 闭运算(先膨胀后腐蚀)
closing = cv2.morphologyEx(binary3,cv2.MORPH_CLOSE,kernel_1)
plt.subplot(121),plt.imshow(binary3),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(closing),plt.title('Close')
plt.xticks([]), plt.yticks([])
plt.show()
## 形态学梯度
gradient = cv2.morphologyEx(binary,cv2.MORPH_GRADIENT,kernel_1)
plt.subplot(121),plt.imshow(binary),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(gradient),plt.title('Gradient')
plt.xticks([]), plt.yticks([])
plt.show()
## 礼帽
kernel_2 = np.ones((9,9),dtype=np.uint8)
tophat = cv2.morphologyEx(binary2,cv2.MORPH_TOPHAT,kernel_2)
plt.subplot(121),plt.imshow(binary2),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(tophat),plt.title('Tophat')
plt.xticks([]), plt.yticks([])
plt.show()
## 黑帽
kernel_2 = np.ones((9,9),dtype=np.uint8)
blackhat = cv2.morphologyEx(binary3,cv2.MORPH_BLACKHAT,kernel_2)
plt.subplot(121),plt.imshow(binary3),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(blackhat),plt.title('Blachat')
plt.xticks([]), plt.yticks([])
plt.show()
## 结构化元素
# Rectangular Kernel
cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
array([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]], dtype=uint8)
# Elliptical Kernel
cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
array([[0, 0, 1, 0, 0],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[0, 0, 1, 0, 0]], dtype=uint8)
# Cross-shaped Kernel
cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5))
array([[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[1, 1, 1, 1, 1],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0]], dtype=uint8)
形态学算法原理:https://blog.csdn.net/Galen_xia/article/details/103461651
图像添加椒盐噪声:https://blog.csdn.net/Galen_xia/article/details/108511120