文章目錄
- 距離變換
- distanceTransform函數
距離變換
如果把二值圖像理解成地形,黑色表示海洋,白色表示陸地,那么陸地上任意一點,到海洋都有一個最近的距離,如下圖所示,對于左側二值圖像來說,【dist-bg】為其白色區域的骨骼;【dist-fg】為黑色區域的骨骼。
實現代碼如下
import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import ascent
import cv2img = ascent().astype(np.uint8)bImgs = {}
th, bImg = cv2.threshold(img, 0, 255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
bImgs[f'otsu({th})'] = bImgbImgs["dist-bg"] = cv2.distanceTransform(bImg, cv2.DIST_L2,5)
bImgs["dist-fg"] = cv2.distanceTransform(255-bImg, cv2.DIST_L2,5)for i,key in enumerate(bImgs,1):plt.subplot(1,3,i)plt.imshow(bImgs[key], cmap='gray')plt.title(key)plt.axis('off')plt.show()
distanceTransform函數
【distanceTransform】函數的功能是,計算當前像素點到零像素點的最短距離,其輸入參數有三,分別是輸入的二值圖像;求解距離的類型,以及掩膜尺寸,一般可設為3或者5。
在一張圖像中,兩點之間的距離有多種計算方式,比如
- a a a 水平和數豎直方向的變化量
- b b b 對角方向的變化量
- c c c 條約移動的變化量
距離變換函數綜合了這三種距離,根據各種距離的權重不同,提供了下面幾種不同的距離類別
distanceType | maskSize | 參數 |
---|---|---|
CV_DIST_C | 3 ( 3 × 3 ) (3\times3) (3×3) | a = 1 , b = 1 a=1, b=1 a=1,b=1 |
CV_DIST_L1 | 3 ( 3 × 3 ) (3\times3) (3×3) | a = 1 , b = 2 a=1, b=2 a=1,b=2 |
CV_DIST_L2 | 3 ( 3 × 3 ) (3\times3) (3×3) | a = 0.955 , b = 1.3693 a=0.955, b=1.3693 a=0.955,b=1.3693 |
CV_DIST_L2 | 5 ( 5 × 5 ) (5\times5) (5×5) | a = 1 , b = 1.4 , c = 2.1969 a=1, b=1.4, c=2.1969 a=1,b=1.4,c=2.1969 |