Opencv实现图像的腐蚀、膨胀及开、闭运算
图像的腐蚀、膨胀及开闭运算
目录
- 图像的腐蚀、膨胀及开闭运算
- 图像的腐蚀、膨胀
- 图像的腐蚀
- 图像的膨胀
- 图像的开、闭运算
- 图像的开运算
- 图像的闭运算
图像的腐蚀、膨胀
图像的腐蚀
-
概念:将图像中的高亮区域或白色部分进行缩减细化,其运行结果图比原图的高亮区域更小,甚至无。(暗部增加)
-
格式:cv2.erode(a,k,iterations=n)
a:图像变量
k:腐蚀区域
iterations:腐蚀次数
代码展示:
a = cv2.imread('at1.png')
kernel = np.ones((3,3),np.uint8)
at1_erode_3 = cv2.erode(a,kernel,iterations=3)
at1_erode_5 = cv2.erode(a,kernel,iterations=1)
cv2.imshow('at1',a)
cv2.imshow('at1',a)
cv2.waitKey(0)
cv2.imshow('at1_erode_3',at1_erode_3)
cv2.waitKey(0)
cv2.waitKey(0)
cv2.imshow('at1_erode_5',at1_erode_5)
cv2.waitKey(0)
s = cv2.imread('sun.png')
kernel = np.ones((3,3),np.uint8)
print(kernel,type(kernel))
s_erode_3 = cv2.erode(s,kernel,iterations=3)
s_erode_5 = cv2.erode(s,kernel,iterations=1)
cv2.imshow('sun',s)
cv2.imshow('sun',s)
cv2.waitKey(0)
cv2.imshow('s_erode_3',s_erode_3)
cv2.waitKey(0)
cv2.imshow('s_erode_5',s_erode_5)
cv2.waitKey(0)
运行结果:
图像的膨胀
-
概念:将图像中的高亮区域或白色部分进行膨胀,其运行结果图比原图的高亮区域更大。(暗部减少)
-
格式:cv2.dilate(a,k,iterations=n)
a:图像变量
k:腐蚀区域
iterations:腐蚀次数
代码展示:
a = cv2.imread('at1.png')
kernel = np.ones((3,3),np.uint8)
cv2.imshow('at1',a)
cv2.waitKey(0)
a_dilate = cv2.dilate(a,kernel,iterations=1)
cv2.imshow('a_dilate',a_dilate)
cv2.waitKey(0)
wenz = cv2.imread('wenz.png')
wenz_dilate = cv2.dilate(wenz,kernel,iterations=1)
cv2.imshow('wenz',wenz)
cv2.waitKey(0)
cv2.imshow('wenz_dilate',wenz_dilate)
cv2.waitKey(0)
运行结果:
图像的开、闭运算
图像的开运算
- 概念:先腐蚀再膨胀
- 格式:cv2.morphologyEx(a,MOPH_OPEN,K)
a:图像变量
k:腐蚀区域
MOPH_OPEN:开运算操作
图像的闭运算
- 概念:先膨胀在腐蚀
- 格式:cv2.morphologyEx(a,MORPH_CLOSE,K)
a:图像变量
k:腐蚀区域
MORPH_CLOSE:闭运算操作
代码展示:
a = cv2.imread('at1.png')
kernel = np.ones((3,3),np.uint8)
a_morph_open = cv2.morphologyEx(a,cv2.MORPH_OPEN,kernel)
a_morph_close = cv2.morphologyEx(a,cv2.MORPH_CLOSE,kernel)
zw1 = cv2.imread('zw1.png')
zw1_morph_open = cv2.morphologyEx(zw1,cv2.MORPH_OPEN,kernel)
zw2 = cv2.imread('zw2.png')
kernel = np.ones((4,4),np.uint8)
zw2_morph_close = cv2.morphologyEx(zw2,cv2.MORPH_CLOSE,kernel)
cv2.imshow('a',a)
cv2.waitKey(0)
cv2.imshow('a_morph_open',a_morph_open)
cv2.waitKey(0)
cv2.imshow('a_morph_close',a_morph_close)
cv2.waitKey(0)
cv2.imshow('zw1',zw1)
cv2.waitKey(0)
cv2.imshow('zw1_morph_open',zw1_morph_open)
cv2.waitKey(0)
cv2.imshow('zw2',zw2)
cv2.waitKey(0)
cv2.imshow('zw2_morph_close',zw2_morph_close)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果: