函数原型
运行形态学操作的核心函数是morphologyEx
。在本例中,我们使用了4个参数(其余使用默认值):
- src : 原 (输入) 图像
- dst: 输出图像
- operation: 需要运行的形态学操作。 我们有5个选项:
- Opening: MORPH_OPEN : 2
- Closing: MORPH_CLOSE: 3
- Gradient: MORPH_GRADIENT: 4
- Top Hat: MORPH_TOPHAT: 5
- Black Hat: MORPH_BLACKHAT: 6
- kernel: 形态学运算的内核。
前一节我们讨论了两种最基本的形态学操作:
- 腐蚀 (Erosion)
- 膨胀 (Dilation)
运用这两个基本操作,我们可以实现更高级的形态学变换。
开运算 (Opening)
开运算是通过先对图像腐蚀再膨胀实现的。
能够排除小团块物体。
代码
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()
原图
开运算
闭运算(Closing)
闭运算是通过先对图像膨胀再腐蚀实现的。
能够排除小型黑洞(黑色区域)。
代码
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()
闭运算
形态梯度(Morphological Gradient)
膨胀图与腐蚀图之差
能够保留物体的边缘轮廓。
代码
#梯度运算 = 膨胀 - 腐蚀
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()
顶帽(Top Hat)
原图像与开运算结果图之差
代码
#礼帽 = 原始如输入 - 开运算
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()
黑帽(Black Hat)
闭运算结果图与原图像之差
代码
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()