图像形态学操作
通常都是二值的图像来做腐蚀操作。腐蚀的大概意思就是往里面缩一些。
import cv2
import matplotlib.pyplot as plt
import numpy as np
#显示图像函数
def cv_show(name,img):
cv2.imshow(name,img)
while cv2.waitKey(100) != 27:# loop if not get ESC
if cv2.getWindowProperty(name,cv2.WND_PROP_VISIBLE) <= 0:
break
cv2.destroyWindow(name)
消除毛刺
img = cv2.imread('dige.png')
cv_show('img',img)
kernel = np.ones((3,3),np.uint8)
erosion = cv2.erode(img,kernel,iterations=1)
cv_show('erosion',erosion)
加粗瑕疵毛刺
img = cv2.imread('dige.png')
kernel = np.ones((3,3),np.uint8)
img_dilate = cv2.dilate(img,kernel,iterations=1)
cv_show('dilate',img_dilate)
以黑白圆圈为例
pie = cv2.imread('pie.png')
cv_show('pie',pie)
kernel = np.ones((30,30),np.uint8)
erosion_1 = cv2.erode(pie,kernel,iterations=1)
erosion_2 = cv2.erode(pie,kernel,iterations=2)
erosion_3 = cv2.erode(pie,kernel,iterations=3)
res = np.hstack((erosion_1,erosion_2,erosion_3))
cv_show('res',res)
开运算、闭运算
# 开:先腐蚀,再膨胀
#这个操作能够将主体被腐蚀地部分补偿回去,但是边缘的毛刺很好的被清除掉。
img = cv2.imread('dige.png')
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
cv_show('opening',opening)
# 闭:先膨胀,再腐蚀
#这个就对边缘的毛刺没有什么清除效果
img = cv2.imread('dige.png')
kernel = np.ones((5,5),np.uint8)
closing = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)
cv_show('closing',closing)
梯度运算
梯度=膨胀-腐蚀
pie = cv2.imread('pie.png')
kernel = np.ones((3,3),np.uint8)
gradient = cv2.morphologyEx(pie,cv2.MORPH_GRADIENT,kernel)
cv_show('gradient',gradient)
礼帽与黑帽
礼帽 = 原始输入-开运算结果
黑帽 = 闭运算-原始输入
#礼帽
kernel = np.ones((7,7),np.uint8)
img = cv2.imread('dige.png')
tophat = cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel)
cv_show('tophat',tophat)
#黑帽
kernel = np.ones((7,7),np.uint8)
img = cv2.imread('dige.png')
balckhat = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel)
cv_show('black',balckhat)