跳转到内容

闭运算

维基百科,自由的百科全书
如果选择灰色圆盘当 B(kernel),对两个深蓝色的正方形做closing,会多出浅蓝色的部分.

在数学形态学中,集合B对集合A的Closing是先dilation再用erosion。

分别表示dilation和erosion。

在影像处理中,closing和opening是用来对影像除噪,这边通常A就是我们输入的影像,B则是kernel。

特性

  • Idempotent,即 .
  • Increasing,如果 , 然后 .
  • Extensive,即 .
  • Translation invariant.

实作

这边对binary image做closing的操作,kernel为5*5大小,4个角落被去掉。

closing不一定要先dilation一次再用erosion一次,也可以使用closing = dilation k times + erosion k times。

当想要closing的洞比较大时,可以使用更高的k次。

def dilation(img):
  img1 = np.zeros((img.shape[0], img.shape[1]), dtype="int")
  for i in range(img.shape[0]):
    for j in range(img.shape[1]):
      if img[i][j]>0:
        row = i-2; col = j-2; # The octogonal 4-5-5-5-4 kernel
        for w in range(5):
          for h in range(5):
            if ( w==0 and h==0 ) or ( w==0 and h==4 ) or ( w==4 and h==0 ) or ( w==4 and h==4 ):
              continue
            else:
              i2 = row + w; j2 = col + h;
              if i2 >= 0 and j2 >= 0 and i2 < img.shape[0] and j2 < img.shape[1]:
                img1[i2][j2] = 255
  return img1

def erosion(img):
  img1 = np.zeros((img.shape[0], img.shape[1]), dtype="int")
  for i in range(img.shape[0]):
    for j in range(img.shape[1]):
        flag = 0
        row = i-2; col = j-2; # The octogonal 4-5-5-5-4 kernel
        for w in range(5):
          for h in range(5):
            if ( w==0 and h==0 ) or ( w==0 and h==4 ) or ( w==4 and h==0 ) or ( w==4 and h==4 ):
              continue
            else:
              i2 = row + w; j2 = col + h;
              if i2 > 0 and j2 > 0 and i2 < img.shape[0] and j2 < img.shape[1]:
                if img[i2][j2] == 0:
                  flag = 1
        if flag == 0:
          img1[i][j] = 255
  return img1
  
def closing(img):
  return erosion(dilation(img))

参考

  • Image Analysis and Mathematical Morphology by Jean Serra, ISBN 0-12-637240-3 (1982)
  • Image Analysis and Mathematical Morphology, Volume 2: Theoretical Advances by Jean Serra, ISBN 0-12-637241-1 (1988)
  • An Introduction to Morphological Image Processing by Edward R. Dougherty, ISBN 0-8194-0845-X (1992)