問題是你必須通過一個整數數組到greycomatrix
,但np.nan
有float
(看看this thread瞭解詳情)。因此,您不能將ROI以外的像素編碼爲NaN
。
處理非矩形ROI的近似解決方法是將ROI外部的像素設置爲0
並使用mahotas庫中的函數haralick
。該函數返回從四個不同的GLCM中提取的13個Haralick特徵,對應於四個2-D方向和距離參數的特定值。
從文檔:
ignore_zeros
可用於具有功能忽略任何零值 像素(作爲背景)。
總之,你需要屏蔽那些落在ROI之外的像素,以及在調用haralick
設置ignore_zeros
到True
。
DEMO
首先,讓我們產生了一些模擬數據:
In [213]: import numpy as np
In [214]: shape = (3, 4)
In [215]: levels = 8
In [216]: np.random.seed(2017)
In [217]: x = np.random.randint(0, levels, size=shape)
In [218]: x
Out[218]:
array([[3, 1, 6, 5],
[2, 0, 2, 2],
[3, 7, 7, 7]])
然後,我們必須刪除所有從圖像中0作爲這種方法的強度爲零級別是爲ROI外部的像素保留的。值得指出的是,合併強度0
和1
成單一強度1
引入結果的不準確性。
In [219]: x[x == 0] = 1
In [220]: x
Out[220]:
array([[3, 1, 6, 5],
[2, 1, 2, 2],
[3, 7, 7, 7]])
接着步驟包括限定用於ROI之外的像素的掩模(在此玩具實例中,圖像的四個角)和那些像素設置爲0
。
In [221]: non_roi = np.zeros(shape=shape, dtype=np.bool)
In [222]: non_roi[np.ix_([0, -1], [0, -1])] = True
In [223]: non_roi
Out[223]:
array([[ True, False, False, True],
[False, False, False, False],
[ True, False, False, True]], dtype=bool)
In [224]: x[non_roi] = 0
In [225]: x
Out[225]:
array([[0, 1, 6, 0],
[2, 1, 2, 2],
[0, 7, 7, 0]])
我們現在可以從非矩形ROI的GLCM的執行特徵提取:
In [226]: import mahotas.features.texture as mht
In [227]: features = mht.haralick(x, ignore_zeros=True)
In [228]: features.size
Out[228]: 52
In [229]: features.ravel()
Out[229]: array([ 0.18 , 5.4 , 0.5254833 , ..., 0.81127812,
-0.68810414, 0.96300727])
這可能是有用的檢查共生矩陣的外觀。例如,「右側像素」GLCM將是:
In [230]: mht.cooccurence(x, 0)
Out[230]:
array([[0, 1, 0, ..., 0, 1, 2],
[1, 0, 2, ..., 0, 1, 0],
[0, 2, 2, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[1, 1, 0, ..., 0, 0, 0],
[2, 0, 0, ..., 0, 0, 2]])