来源:https://www.petfinder.com/cats/cat-grooming/
我尝试在Python中接收与MATLAB中相同的函数graycomatrix和graycrops的结果。但是结果不同,我无法编写代码来重复MATLAB的结果。在
我需要GLCM功能,如对比度、相关性、能量和同质性。在
任何建议都非常感谢。在
MATLAB中的示例代码:
% GLCM feature extraction
offset_GLCM = [0 1; -1 1; -1 0; -1 -1];
offset = [1*offset_GLCM ; 2*offset_GLCM; 3*offset_GLCM];
img = rgb2gray(imread('cat.jpg'));
Grauwertmatrix = graycomatrix(img,'NumLevels', 12, 'GrayLimits', [], 'Offset',offset);
GrauwertStats = graycoprops(Grauwertmatrix);
GLCMFeatureVector = [mean(GrauwertStats.Contrast) mean(GrauwertStats.Correlation) mean(GrauwertStats.Energy) mean(GrauwertStats.Homogeneity)];
disp(GLCMFeatureVector);
上面的代码返回:
^{pr2}$现在我希望在Python中得到完全相同的结果。我使用Python代码:
# GLCM feature extraction
import numpy as np
from skimage import feature, io
from sklearn import preprocessing
img = io.imread("cat.jpg", as_grey=True)
S = preprocessing.MinMaxScaler((0,11)).fit_transform(img).astype(int)
Grauwertmatrix = feature.greycomatrix(S, [1,2,3], [0, np.pi/4, np.pi/2, 3*np.pi/4], levels=12, symmetric=False, normed=True)
ContrastStats = feature.greycoprops(Grauwertmatrix, 'contrast')
CorrelationtStats = feature.greycoprops(Grauwertmatrix, 'correlation')
HomogeneityStats = feature.greycoprops(Grauwertmatrix, 'homogeneity')
ASMStats = feature.greycoprops(Grauwertmatrix, 'ASM')
print([np.mean(ContrastStats), np.mean(CorrelationtStats),\
np.mean(ASMStats), np.mean(HomogeneityStats)])
但我得到的结果是:
[1.7607, 0.8844, 0.0429, 0.7085]
另一个例子。原始图像的不同结果。原因是MATLAB默认处理图像,而Python不处理。如何在Python中得到与MATLAB相同的结果?:
MATLAB软件:
>> img = rgb2gray(imread('cat.png'));
>> [Grauwertmatrix, S] = graycomatrix(img,'NumLevels',12,'GrayLimits',[0,12],'Offset',[0,1]);
>> Grauwertmatrix(1:5,1:5)
ans =
4 7 4 8 0
9 33 22 13 10
5 18 16 10 10
2 16 11 22 13
4 12 11 14 14
Python:
>>> from skimage import io, feature
>>> img = io.imread("cat.png", as_grey=True)
>>> Grauwertmatrix = feature.greycomatrix(img, distances=[1], angles=[0], levels=12, symmetric=False, normed=False)
>>> Grauwertmatrix[0:5, 0:5, 0, 0]
array([[299720, 2, 0, 0, 0],
[ 2, 1, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]], dtype=uint32)
使用Matlab和Python计算的GLCM特征是不同的,因为用Matlab代码对原始图像进行预处理(即转换为灰度、缩放和重新量化)的结果与Python代码(即array
S
)的结果不同。下面的片段说明了这一点:Matlab
Python
^{pr2}$最后,我建议您使用无损图像格式(如BMP或PNG),以避免由于JPG解压缩而产生的潜在差异。在
解决方法
为了通过Matlab和Python获得相同的结果,您应该在两种情况下使用相同的预处理图像。例如,可以这样生成这样的图像:
请注意,resulting image的对比度非常低,因为强度值在0到11之间。在
为了让Matlab的}(而不是
graycomatrix
正确缩放此图像,您需要传递'NumLevels',12
和{[0,11]
):Python返回相同的结果:
编辑
针对您的评论,我认为不可能通过Matlab和Python从原始RGB图像中获得相同的结果,因为灰度转换的执行方式不同。文件中明确说明了这一点:
Matlab的^{} :
scikit图像的^{} :
相关问题 更多 >
编程相关推荐