Search code examples
pythonnumpypython-imaging-libraryscikit-imageglcm

How to use the scikit-image greycomatrix() -function in python?


I'm trying to compute grey level co-occurrence matrices from images for feature extraction. I'm using greycomatrix for the task but there seems to be something I don't understand about the process since I'm getting the following error:

ValueError: buffer source array is read-only

(The full trace can be found below)

So here's what I've done:

Converting the (PIL) image to grayscale with 8 quantization levels:

greyImg = img.convert('L', colors=8)

And then compute the glcm matrices:

glcm = greycomatrix(greyImg, distances=[1], angles=[0, np.pi/4, np.pi/2], 
                    symmetric=True, normed=True)

This results in a rather cryptic error:

glcm = greycomatrix(img, distances=[1], angles=[0, np.pi/4, np.pi/2], levels=256, symmetric=True, normed=True)

_glcm_loop(image, distances, angles, levels, P)

File "skimage/feature/_texture.pyx", line 18, in skimage.feature._texture._glcm_loop

File "stringsource", line 654, in View.MemoryView.memoryview_cwrapper

File "stringsource", line 349, in View.MemoryView.memoryview._cinit__ ValueError: buffer source array is read-only

I've been trying to tingle with the paremeters but I can't seem to figure out, why this happens. What would be the correct way to compute the glcm-matrix?

Update

The problem was in the grayscale conversion. The following changes were required:

import numpy as np

greyImg = np.array(img.convert('L', colors=8))

Solution

  • The function greycomatrix expects a NumPy ndarray rather than a PIL Image object. You need to convert greyImg like this:

    import numpy as np
    
    greyImg = np.asarray(img.convert('L', colors=8))