运行形态学操作的核心函数是morphologyEx
。在本例中,我们使用了4个参数(其余使用默认值):
前一节我们讨论了两种最基本的形态学操作:
运用这两个基本操作,我们可以实现更高级的形态学变换。
开运算是通过先对图像腐蚀再膨胀实现的。
能够排除小团块物体。
import cv2
import matplotlib.pyplot as plt
import numpy as np
img =cv2.imread("./cycle.png",cv2.IMREAD_COLOR)
cv2.imshow("cycle",img)
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)#开运算: 先腐蚀后膨胀
closing = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)#闭运算:先膨胀后腐蚀
cv2.imshow("opening",opening)
cv2.imshow("closing",closing)
cv2.waitKey(0)
cv2.destroyAllWindows()
闭运算是通过先对图像膨胀再腐蚀实现的。
能够排除小型黑洞(黑色区域)。
import cv2
import matplotlib.pyplot as plt
import numpy as np
img =cv2.imread("./cycle.png",cv2.IMREAD_COLOR)
cv2.imshow("cycle",img)
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)#开运算: 先腐蚀后膨胀
closing = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)#闭运算:先膨胀后腐蚀
cv2.imshow("opening",opening)
cv2.imshow("closing",closing)
cv2.waitKey(0)
cv2.destroyAllWindows()
膨胀图与腐蚀图之差
能够保留物体的边缘轮廓。
#梯度运算 = 膨胀 - 腐蚀
import cv2
import matplotlib.pyplot as plt
import numpy as np
img =cv2.imread("./cycle.png",cv2.IMREAD_COLOR)
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
cv2.imshow("cycle",opening)
kernel = np.ones((5,5),np.uint8)
gradient = cv2.morphologyEx(opening,cv2.MORPH_GRADIENT,kernel)
cv2.imshow("gradient",gradient)
cv2.waitKey(0)
cv2.destroyAllWindows()
原图像与开运算结果图之差
#礼帽 = 原始如输入 - 开运算
import cv2
import matplotlib.pyplot as plt
import numpy as np
img =cv2.imread("./cycle.png",cv2.IMREAD_COLOR)
cv2.imshow("cycle",img)
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
cv2.imshow("opening",opening)
tophat = cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel)
cv2.imshow("tophat",tophat)
cv2.waitKey(0)
cv2.destroyAllWindows()
闭运算结果图与原图像之差
import cv2
import matplotlib.pyplot as plt
import numpy as np
img =cv2.imread("./cycle.png",cv2.IMREAD_COLOR)
cv2.imshow("cycle",img)
#kernel = np.ones((5,5),np.uint8)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
closing = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)
cv2.imshow("closing",closing)
blackhat = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel)
cv2.imshow("blackhat",blackhat)
cv2.waitKey(0)
cv2.destroyAllWindows()