数学形态运算中,最常见的基本运算有七种, 分别为:腐蚀、膨胀、开运算、闭运算、击中、细化和粗化, 它们是全部形态学的基础。腐蚀和膨胀,看上去好像是一对互逆的操作,实际上,这两种操作不具有互逆的关系。 开运算和闭运算正是依据腐蚀和膨胀的不可逆性,演变而来的。先腐蚀后膨胀的过程就称为开运算。 闭运算是通过对腐蚀和膨胀的另一种不同次序的执行而得到的, 闭运算是先膨胀后腐蚀的过程,其功能是用来填充物体内细小空洞、连接邻近物体、平滑其边界, 同时不明显改变不明显改变其面积。 参考代码如下所示:
import
matplotlib.pyplot
as
plt
import
numpy
as
np
import
cv2
img
=
cv2.imread(
'./imgs/11.jpg'
,
0
)
kernel
=
np.ones((
5
,
5
),np.uint8)
dilate_img
=
cv2.dilate(img,kernel,
iterations
=
1
)
erosion_img
=
cv2.erode(img,kernel,
iterations
=
1
)
opening_img
=
cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
closing_img
=
cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
f,(a1,a2,a3,a4,a5)
=
plt.subplots(
1
,
5
,
figsize
=
(
600
,
400
))
a1.set_title(
"oraginal image"
)
a1.imshow(img,
cmap
=
"gray"
)
a2.set_title(
"dilate_img"
)
a2.imshow(dilate_img,
cmap
=
"gray"
)
a3.set_title(
"erosion_img"
)
a3.imshow(erosion_img,
cmap
=
"gray"
)
a4.set_title(
"opening_img"
)
a4.imshow(opening_img,
cmap
=
"gray"
)
a5.set_title(
"closing_img"
)
a5.imshow(closing_img,
cmap
=
"gray"
)
plt.show()