图像形态学处理包括腐蚀、膨胀、开运算、闭运算、形态学梯度、礼帽(顶帽)、黑帽等运算。
1、腐蚀
腐蚀可以理解为前景像素会被腐蚀为背景像素,以白色255为前景,得到的效果就是白色变小、变细,黑色变大变粗:
import cv2
import numpy as np
img = cv2.imread('lena.jpg',0)
kernel = np.ones((5,5),np.uint8)
erosion = cv2.erode(img,kernel,iterations = 1)
cv2.imshow("img", img)
cv2.imshow("erosion", erosion)
cv2.waitKey(0)
cv2.destroyAllWindows()
2、膨胀
与腐蚀相反的操作,效果是前景变大变粗,背景变小变细:
import cv2
import numpy as np
img = cv2.imread('lena.jpg',0)
kernel = np.ones((5,5),np.uint8)
dilation = cv2.dilate(img,kernel,iterations = 1)
cv2.imshow("img", img)
cv2.imshow("dilation ", dilation )
cv2.waitKey(0)
cv2.destroyAllWindows()
3、闭运算
闭运算是先膨胀后腐蚀,这样的处理结果是前景中的小黑洞会被填充: import cv2
import numpy as np
img = cv2.imread('lena.jpg',0)
kernel = np.ones((5,5),np.uint8)
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
cv2.imshow("img", img)
cv2.imshow("closing ", closing )
cv2.waitKey(0)
cv2.destroyAllWindows()
4、开运算
开运算与闭运算相对,是先腐蚀后膨胀,效果是讲背景中的小亮点去掉:
import numpy as np
img = cv2.imread('lena.jpg',0)
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
cv2.imshow("img", img)
cv2.imshow("opening", opening )
cv2.waitKey(0)
cv2.destroyAllWindows()
5、形态学梯度
形态学梯度做的处理是一幅图像的膨胀与腐蚀做差得到:
import numpy as np
img = cv2.imread('lena.jpg',0)
kernel = np.ones((5,5),np.uint8)
gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)
cv2.imshow("img", img)
cv2.imshow("gradient", gradient)
cv2.waitKey(0)
cv2.destroyAllWindows()
6、顶帽
顶帽是指原图与开运算结果做差:
import numpy as np
img = cv2.imread('lena.jpg',0)
kernel = np.ones((5,5),np.uint8)
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
cv2.imshow("img", img)
cv2.imshow("tophat ", tophat)
cv2.waitKey(0)
cv2.destroyAllWindows()
7、黑帽
黑帽则是与顶帽相对,闭运算与原图做差:
import numpy as np
img = cv2.imread('lena.jpg',0)
kernel = np.ones((5,5),np.uint8)
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
cv2.imshow("img", img)
cv2.imshow("tophat ", tophat)
cv2.waitKey(0)
cv2.destroyAllWindows()
8、结构化元素
前面的几个处理中都有一个核,这个核都是用Numpy来构造的矩形核,其实还可以通过OpenCV提供的cv2.getStructuringElement()来获取其它形状的核:
# 矩形核
cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
# 椭圆形
cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
# 十字交叉
cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5))
南风之薰兮,
可以解吾民之愠兮。
南风之时兮,
可以阜吾民之财兮。
上善若水,为而不争。