Search code examples
pythonimage-processingtuplesscikit-image

How can I fix "tuple index out of range" while doing image segmentation?


I'm learning that tutorial http://scikit-image.org/docs/dev/auto_examples/segmentation/plot_label.html#sphx-glr-auto-examples-segmentation-plot-label-py

The beggining of the code in the tutorial is :

%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

from skimage import data
from skimage.filters import threshold_otsu
from skimage.segmentation import clear_border
from skimage.measure import label, regionprops
from skimage.morphology import closing, square
from skimage.color import label2rgb

image = data.coins()[50:-50, 50:-50]
#  apply threshold
thresh = threshold_otsu(image)
bw = closing(image > thresh, square(3))

and I want to apply it to my image which is a .jpg . But it doesn't work and I get on IPython a long message with at the end :

IndexError: tuple index out of range

I compared

print(data.coins()[50:-50, 50:-50].shape)

(203L, 284L)

and

import mahotas as mh
image=mh.imread('image.jpg')
print(image.shape)

(520L, 704L, 3L)

Am I right to think that the difference comes from the difference in the dimension ? And what can I do in order to fix that ?

Besides that even now I read http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_closing it's not clear for me what square(3) means in closing. Could you explain me that plz ?


Solution

  • Try converting to greyscale after loading:

    from skimage.color import rgb2gray
    
    image = rgb2gray(data.coins()[50:-50, 50:-50]) 
    

    The following:

    square(3) 
    

    just means a 3x3 square matrix of 1s:

    array([[1, 1, 1],
           [1, 1, 1],
           [1, 1, 1]], dtype=uint8)