图像膨胀、腐蚀、开运算、闭运算---python.opencv

结构元素

在图像处理中,常常需要结构元素作为辅助,可以把卷积核也看成一种结构元素,例如在均值滤波器中,卷积核为:

\frac{1}{9}\begin{bmatrix} 1 & 1 & 1\\ 1&1 &1 \\ 1 & 1& 1 \end{bmatrix}

在下面要介绍的膨胀与腐蚀运算中,也需要用到结构元素,一般的结构元素为矩形、十字形、椭圆形。在python中可以调用cv2.getStructuringElement()函数获取结构元素。

import cv2 as cv2
import matplotlib.pyplot as plt
import numpy as np

def cross(size1,size2): #十字形
    element = cv2.getStructuringElement(cv2.MORPH_CROSS,(size1,size1))
    return element

def ellipse(size1,size2): #椭圆形
    element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(size1,size2))
    return element

def rect(size1,size2):   #矩形
    element = cv2.getStructuringElement(cv2.MORPH_RECT,(size1,size2))
    return element

膨胀

膨胀即是将图像进行某种程度上的拓宽,即A⊕B,描述为集合B对集合A的膨胀,公式为:

A\oplus B =\{​{}z\|(\hat{B}_{z}\cap A\neq \O )\}


即以B的中心点为运动点,使B在A平面内运动,运算结果为使得A与B存在交集的所有此运动点的集合,例如:

腐蚀

腐蚀即是将图像进行某种程度上的缩减,,即AΘB描述为集合B对集合A的腐蚀,公式为:

A\ominus B =\{​{}z\|(\hat{B}_{z}\subseteq A\}

即以B的中心点为运动点,使B在A平面内运动,运算结果为使得A全包含B的此中心点的集合,例如:

可以分别使用python中的cv2.erode()与cv2.dilate()完成膨胀与腐蚀操作:

def erode(img,kernel):  #膨胀  kernel为结构元素
    eroded = cv2.erode(img,kernel)
    return eroded

def dilate(img,kernel):  #腐蚀
    dilated = cv2.dilate(img,kernel)
    return dilated

需要注意的是,上述函数中的img都需要二值图像,故我们需先得到二值图像,二值图像的求得方法参照其他文章。

为了显示这两个运算的作用,进行以下例子:

plt.subplot(3,1,1)
plt.imshow(0_1_image,plt.cm.gray)  
plt.xticks([]),plt.yticks([])
plt.title('0-1 image')

#以3×3的矩形为结构元素
erode_image_rect=erode(0_1_image,rect(3,3))
dilate_image_rect=dilate(0_1_image,rect(3,3))

plt.subplot(3,1,2)
plt.imshow(erode_image_rect,plt.cm.gray)
plt.xticks([]),plt.yticks([])
plt.title('erode_image_rect')

plt.subplot(3,1,3)
plt.imshow(dilate_image_rect,plt.cm.gray)
plt.xticks([]),plt.yticks([])
plt.title('dilate_image_rect')
plt.show()

开运算、闭运算

开运算:先进行腐蚀运算,再进行膨胀运算,即A○B,公式为:

A\bigcirc B=(A\ominus B)\oplus B

闭运算:先进行膨胀运算,再进行腐蚀运算,即A•B,公式为:

A\bullet B=(A\oplus B)\ominus B

可以使用python中的cv2.morphologyEx()函数进行运算:

def opening(image,kernel):  #开运算
    opening =cv2.morphologyEx(image,cv2.MORPH_OPEN,kernel)
    return opening

def closing(image,kernel):   #闭运算
    closing = cv2.morphologyEx(image,cv2.MORPH_CLOSE,kernel)
    return closing

同理,image也需要为二值图像,例子:

open_image=opening(0_1_image,rect(3,3))
closing_image=closing(0_1_image,rect(3,3))

plt.subplot(3,1,1)
plt.imshow(0_1_image,plt.cm.gray)
plt.xticks([]),plt.yticks([])
plt.title('0-1 image')
plt.xticks([]),plt.yticks([])

plt.subplot(3,1,2)
plt.imshow(open_image,plt.cm.gray)
plt.title('open_image')
plt.xticks([]),plt.yticks([])


plt.subplot(3,1,3)
plt.imshow(closing_image,plt.cm.gray)
plt.title('closing_image')
plt.xticks([]),plt.yticks([])
plt.show()

 

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值