我想使用python(numpy)查找GLCM矩阵 我已经编写了这段代码,它从四个角度给了我正确的结果,但是它非常慢,用演示128x128处理1000张图片大约需要35分钟
def getGLCM(image, distance, direction):
npPixel = np.array(image) // image as numpy array
glcm = np.zeros((255, 255), dtype=int)
if direction == 1: # direction 90° up ↑
for i in range(distance, npPixel.shape[0]):
for j in range(0, npPixel.shape[1]):
glcm[npPixel[i, j], npPixel[i-distance, j]] += 1
elif direction == 2: # direction 45° up-right ↗
for i in range(distance, npPixel.shape[0]):
for j in range(0, npPixel.shape[1] - distance):
glcm[npPixel[i, j], npPixel[i - distance, j + distance]] += 1
elif direction == 3: # direction 0° right →
for i in range(0, npPixel.shape[0]):
for j in range(0, npPixel.shape[1] - distance):
glcm[npPixel[i, j], npPixel[i, j + distance]] += 1
elif direction == 4: # direction -45° down-right ↘
for i in range(0, npPixel.shape[0] - distance):
for j in range(0, npPixel.shape[1] - distance):
glcm[npPixel[i, j], npPixel[i + distance, j + distance]] += 1
return glcm
我需要帮助以使此代码更快 谢谢。
答案 0 :(得分:1)
您的代码中有一个错误。您需要将灰度共生矩阵的初始化更改为glcm = np.zeros((256, 256), dtype=int)
,否则,如果要处理的图像包含一些强度为255
的像素,则函数getGLCM
将抛出一个错误。
这是一个纯NumPy实现,可通过矢量化提高性能:
def vectorized_glcm(image, distance, direction):
img = np.array(image)
glcm = np.zeros((256, 256), dtype=int)
if direction == 1:
first = img[distance:, :]
second = img[:-distance, :]
elif direction == 2:
first = img[distance:, :-distance]
second = img[:-distance, distance:]
elif direction == 3:
first = img[:, :-distance]
second = img[:, distance:]
elif direction == 4:
first = img[:-distance, :-distance]
second = img[distance:, distance:]
for i, j in zip(first.ravel(), second.ravel()):
glcm[i, j] += 1
return glcm
如果您愿意使用其他软件包,强烈建议您使用scikit-image的greycomatrix。如下所示,这将计算速度提高了两个数量级。
In [93]: from skimage import data
In [94]: from skimage.feature import greycomatrix
In [95]: img = data.camera()
In [96]: a = getGLCM(img, 1, 1)
In [97]: b = vectorized_glcm(img, 1, 1)
In [98]: c = greycomatrix(img, distances=[1], angles=[-np.pi/2], levels=256)
In [99]: np.array_equal(a, b)
Out[99]: True
In [100]: np.array_equal(a, c[:, :, 0, 0])
Out[100]: True
In [101]: %timeit getGLCM(img, 1, 1)
240 ms ± 1.16 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [102]: %timeit vectorized_glcm(img, 1, 1)
203 ms ± 3.11 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [103]: %timeit greycomatrix(img, distances=[1], angles=[-np.pi/2], levels=256)
1.46 ms ± 15.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)