腐蚀操作
import cv2 as cv import numpy as np img = cv.imread('dige.png') kernel = np.ones((5, 5), np.uint8) erosion = cv.erode(img, kernel, iterations = 1) res = np.hstack((img, erosion)) cv.imshow('res', res) cv.waitKey(0) cv.destroyAllWindows()
右边是处理后的结果,白色线条没有了,字体也更加苗条了。
erosion = cv.erode(img, kernel, iterations = 1) :腐蚀函数。 iterations = 1 表示迭代次数为1,迭代次数越高,腐蚀程度越厉害。
再来看一个圆形腐蚀操作例子。
import cv2 as cv import numpy as np img = cv.imread('pie.png') kernel = np.ones((30, 30), np.uint8) erosion_1 = cv.erode(img, kernel, iterations = 1) erosion_2 = cv.erode(img, kernel, iterations = 2) erosion_3 = cv.erode(img, kernel, iterations = 3) res = np.hstack((erosion_1, erosion_2, erosion_3)) cv.imshow('res', res) cv.waitKey(0) cv.destroyAllWindows()
膨胀操作
import cv2 as cv import numpy as np img = cv.imread('dige.png') kernel = np.ones((3, 3), np.uint8) erosion = cv.erode(img, kernel, iterations = 1) # 先腐蚀 dilate = cv.dilate(erosion, kernel, iterations = 1) # 再膨胀 res = np.hstack((img, erosion, dilate)) cv.imshow('res', res) cv.waitKey(0) cv.destroyAllWindows()
从左到右,依次是:原图,腐蚀,膨胀。 dilate = cv.dilate(erosion, kernel, iterations = 1) 是膨胀函数。
由于腐蚀让原图线条变细了,膨胀又可以让线条还原。
开,闭运算
import cv2 as cv import numpy as np img = cv.imread('dige.png') kernel = np.ones((5, 5), np.uint8) opening = cv.morphologyEx(img, cv.MORPH_OPEN, kernel) # 开运算 closing = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel) # 闭运算 res = np.hstack((img, opening, closing)) cv.imshow('res', res) cv.waitKey(0) cv.destroyAllWindows()
从左到右依次是:原图,开运算,闭运算。
opening = cv.morphologyEx(img, cv.MORPH_OPEN, kernel) :开运算,先腐蚀,后膨胀
closing = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel) :闭运算,先膨胀,后腐蚀
梯度运算
import cv2 as cv import numpy as np img = cv.imread('pie.png') kernel = np.ones((3, 3), np.uint8) gradient = cv.morphologyEx(img, cv.MORPH_GRADIENT, kernel) cv.imshow('gradient', gradient) cv.waitKey(0) cv.destroyAllWindows()
梯度运算简单来说,就是将一张图片的膨胀之后,再减去原来图片的腐蚀的结果,得到的就是上图。
礼帽,黑帽
import cv2 as cv import numpy as np img = cv.imread('dige.png') kernel = np.ones((3, 3), np.uint8) tophat = cv.morphologyEx(img, cv.MORPH_TOPHAT, kernel) # 礼帽 blackhat = cv.morphologyEx(img, cv.MORPH_BLACKHAT, kernel) # 黑帽 res = np.hstack((img, tophat, blackhat)) cv.imshow('res', res) cv.waitKey(0) cv.destroyAllWindows()
tophat = cv.morphologyEx(img, cv.MORPH_TOPHAT, kernel) # 礼帽 :礼帽=原始输入-开运算
blackhat = cv.morphologyEx(img, cv.MORPH_BLACKHAT, kernel) # 黑帽 :黑帽=闭运算-原始输入