2

我想使用 python (numpy) 找到 GLCM 矩阵我已经编写了这段代码,它从四个角度给了我一个正确的结果,但是速度很慢,处理 1000 张带有恶魔 128x128 的图片大约需要 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

我需要帮助以使此代码更快谢谢。

4

1 回答 1

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 的graycomatrix。如下所示,这将计算速度提高了两个数量级。

演示

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)
于 2019-05-23T14:53:49.870 回答