腐蚀与膨胀 # 腐蚀API: erode(img,kernel,iterations=1) iterations:执行腐蚀次数 # 获得卷积核 getStructuringElement(type,size) size值为:(3,3)(5,5) type: MORPH_RECT常用,矩形卷积核 MORPH_ELLIPSE椭圆卷积核 MORPH_CROSS十字架卷积核 # 膨胀API: dilate(img,kernel,iterations=1)
腐蚀:
import cv2 as cv
import numpy as np
img = cv.imread('./img/houmo.png')
img1 = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
# 构造卷积核
kernel = cv.getStructuringElement(cv.MORPH_RECT,(3,3))
print(kernel)
# kernel = np.ones((3,3),np.uint8)
dst = cv.erode(img1,kernel,iterations=1)
cv.imshow('img1',img1)
cv.imshow('dst',dst)
cv.waitKey(0)
膨胀:
import cv2 as cv
import numpy as np
img = cv.imread('./img/houmo.png')
img1 = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
dst1 = cv.adaptiveThreshold(img1,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,7,0)
# 构造卷积核
kernel = cv.getStructuringElement(cv.MORPH_RECT,(3,3))
print(kernel)
# kernel = np.ones((3,3),np.uint8)
dst = cv.erode(dst1,kernel,iterations=1)
dst2 = cv.dilate(dst,kernel,iterations=1)
cv.imshow('img1',img1)
cv.imshow('dst',dst)
cv.imshow('dst1',dst1)
cv.imshow('dst2',dst2)
cv.waitKey(0)