基于Python的OpenCV学习
第三章、图像形态学处理
00_思维导图
01_cv2.erode
import cv2
import numpy as np
import matplotlib.pyplot as plt
img1 = cv2.imread('dige.png')
kernel1 = np.ones((3,3))
img2 = cv2.erode(img1,kernel1,iterations=1)
img3 = cv2.erode(img1,kernel1,iterations=2)
img4 = cv2.erode(img1,kernel1,iterations=3)
img_list = [img1,img2,img3,img4]
img_tittle = ['init','1','2','3']
for i in range(4):
plt.subplot(1,4,i+1)
plt.imshow(img_list[i])
plt.title(img_tittle[i])
plt.show()
cv2.waitKey()
cv2.destroyAllWindows()
运行结果:
02_cv2.dilate
import cv2
import numpy as np
import matplotlib.pyplot as plt
img1 = cv2.imread('dige.png')
kernel1 = np.ones((3,3))
img2 = cv2.erode(img1,kernel1,iterations=2)
img3 = cv2.dilate(img2,kernel1,iterations=2)
img4 = cv2.dilate(img2,kernel1,iterations=4)
img_list = [img1,img2,img3,img4]
img_tittle = ['init','erode','dilate*2','dilate*4']
for i in range(4):
plt.subplot(1,4,i+1)
plt.imshow(img_list[i])
plt.title(img_tittle[i])
plt.show()
cv2.waitKey()
cv2.destroyAllWindows()
运行结果:
03_cv2.morphologyEx
import cv2
import numpy as np
import matplotlib.pyplot as plt
img1 = cv2.imread('dige.png')
kernel1 = np.ones((3,3))
img2 = cv2.morphologyEx(img1,cv2.MORPH_OPEN,kernel1)
img3 = cv2.morphologyEx(img1,cv2.MORPH_CLOSE,kernel1)
img4 = cv2.morphologyEx(img1,cv2.MORPH_GRADIENT,kernel1)
img5 = cv2.morphologyEx(img1,cv2.MORPH_TOPHAT,kernel1)
img6 = cv2.morphologyEx(img1,cv2.MORPH_BLACKHAT,kernel1)
img_list = [img1,img2,img3,img4,img5,img6]
img_tittle = ['init','open','close','gradient','tophat','blackhat']
for i in range(6):
plt.subplot(2,3,i+1)
plt.imshow(img_list[i])
plt.title(img_tittle[i])
plt.show()
cv2.waitKey()
cv2.destroyAllWindows()
运行结果: