本节的运算都需要使用该函数cv2.morphologyEx:

morphologyEx(src,op,kernel,dst = None,anchor = None,iterations = None,borderType = None,borderValue = None)

决定开运算和闭运算主要取决于第二个参数:
图片alt

一、开运算

对图像进行先腐蚀后膨胀的操作称为开运算。作用:消除细小物体、在窄区域分离物体、平滑大物体边界等。

import cv2
import numpy as np

src_img = cv2.imread("2-1.jpg", cv2.IMREAD_UNCHANGED)

cv2.imshow("src_img", src_img)

k1 = np.ones((3, 3), np.uint8)
k2 = np.ones((5, 5), np.uint8)

res_img_1 = cv2.morphologyEx(src_img, cv2.MORPH_OPEN, k1)
res_img_2 = cv2.morphologyEx(src_img, cv2.MORPH_OPEN, k2)

cv2.imshow("res_img_1", res_img_1)
cv2.imshow("res_img_2", res_img_2)

cv2.waitKey(0)
cv2.destroyAllWindows()

图片alt

当我们的卷积核为3时,还有两条线,当卷积核为5时,噪声就去除了。

二、闭运算

对图片先膨胀后腐蚀的操作称为闭运算。作用:填充物体空洞、消除噪声、连接邻近物体、平滑边界等。

import cv2
import numpy as np

src_img = cv2.imread("2-2.jpg", cv2.IMREAD_UNCHANGED)

cv2.imshow("src_img", src_img)

k1 = np.ones((3, 3), np.uint8)
k2 = np.ones((5, 5), np.uint8)

res_img_1 = cv2.morphologyEx(src_img, cv2.MORPH_CLOSE, k1)
res_img_2 = cv2.morphologyEx(src_img, cv2.MORPH_CLOSE, k2)

cv2.imshow("res_img_1", res_img_1)
cv2.imshow("res_img_2", res_img_2)

cv2.waitKey(0)
cv2.destroyAllWindows()

图片alt

通过闭运算可以去掉白色里面小黑点。作用:得到图片的轮廓。

import cv2
import numpy as np

src_img = cv2.imread("2-3.jpg", cv2.IMREAD_UNCHANGED)

cv2.imshow("src_img", src_img)

k1 = np.ones((3, 3), np.uint8)


res_img_1 = cv2.morphologyEx(src_img, cv2.MORPH_GRADIENT, k1)


cv2.imshow("res_img_1", res_img_1)

cv2.waitKey(0)
cv2.destroyAllWindows()

图片alt

四、顶帽运算

先对图片进行开运算,再用原始图像减去开运算后的图像就是顶帽运算。作用:得到噪声图像。

import cv2
import numpy as np

src_img = cv2.imread("2-1.jpg", cv2.IMREAD_UNCHANGED)

cv2.imshow("src_img", src_img)

k1 = np.ones((3, 3), np.uint8)


res_img_1 = cv2.morphologyEx(src_img, cv2.MORPH_TOPHAT, k1)


cv2.imshow("res_img_1", res_img_1)

cv2.waitKey(0)
cv2.destroyAllWindows()

图片alt

五、黑帽运算

先对图像进行闭运算,再用闭运算后的图像减去原始图像就是黑帽运算。作用:得到内部的小孔或黑色点。

import cv2
import numpy as np

src_img = cv2.imread("2-2.jpg", cv2.IMREAD_UNCHANGED)

cv2.imshow("src_img", src_img)

k1 = np.ones((3, 3), np.uint8)


res_img_1 = cv2.morphologyEx(src_img, cv2.MORPH_BLACKHAT, k1)


cv2.imshow("res_img_1", res_img_1)

cv2.waitKey(0)
cv2.destroyAllWindows()

图片alt