腐蚀操作
#腐蚀操作 import cv2 import numpy as np img=cv2.imread("d:/ke.png") kernel = np.ones((3,3),np.uint8) erosion = cv2.erode(img,kernel,iterations = 1)#腐蚀操作 iterations控制腐蚀程度 erosion1 = cv2.erode(img,kernel,iterations = 2) erosion2 = cv2.erode(img,kernel,iterations = 3) res=np.hstack((img,erosion,erosion1,erosion2)) cv2.imshow('erosion', res) cv2.waitKey(0) cv2.destroyAllWindows()
膨胀操作
import cv2 import numpy as np img=cv2.imread("d:/ke.png") kernel=np.ones((3,3),np.uint8) img_diate=cv2.dilate(img,kernel,iterations=1) #膨胀操作 img_diate1=cv2.dilate(img,kernel,iterations=2) img_diate2=cv2.dilate(img,kernel,iterations=3) res=np.hstack((img_diate,img_diate1,img_diate2)) #水平展示 cv2.imshow("ditae",res) cv2.waitKey(0) cv2.destroyAllWindows()
开闭运算
import cv2 import numpy as np img=cv2.imread("d:/ke.png") kernel=np.ones((3,3),np.uint8) open=cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)#开运算:先腐蚀,后膨胀 close=cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)#关运算:先膨胀,后腐蚀 res=np.hstack((open,close)) cv2.imshow("kai vs close",res) cv2.waitKey(0) cv2.destroyAllWindows()
梯度运算
#梯度运算 import cv2 import numpy as np img=cv2.imread("d:/ke.png") kernel=np.ones((3,3),np.uint8) dilate=cv2.dilate(img,kernel,iterations=3) #膨胀 erosion=cv2.erode(img,kernel,iterations=3) #腐蚀 gradient=cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel) #梯度 res=np.hstack((dilate,erosion,gradient)) cv2.imshow("show",res) cv2.waitKey(0) cv2.destroyAllWindows()
礼帽与黑帽
礼帽 = 原始输入-开运算结果
黑帽 = 闭运算-原始输入
import cv2 import numpy as np img=cv2.imread("d:/ke.png") kernel=np.ones((3,3),np.uint8) tophar=cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel) #礼帽 blackhar=cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel) #黑帽 res=np.hstack((tophar,blackhar)) cv2.imshow("hat",res) cv2.waitKey(0) cv2.destoryAllWindows()