Skip to main content
 首页 » 编程设计

python之使用 numpy 提取 glcm 矩阵

2024年11月24日8hnrainll

我想使用 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 

我需要帮助使这段代码更快 谢谢。

请您参考如下方法:

您的代码中存在错误。您需要将灰度级共生矩阵的初始化更改为 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)