结构元素
在图像处理中,常常需要结构元素作为辅助,可以把卷积核也看成一种结构元素,例如在均值滤波器中,卷积核为:
在下面要介绍的膨胀与腐蚀运算中,也需要用到结构元素,一般的结构元素为矩形、十字形、椭圆形。在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的膨胀,公式为:
即以B的中心点为运动点,使B在A平面内运动,运算结果为使得A与B存在交集的所有此运动点的集合,例如:
腐蚀
腐蚀即是将图像进行某种程度上的缩减,,即AΘB描述为集合B对集合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•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()