Search code examples
pythonplotshapesimshowsimpleitk

TypeError: Invalid shape (14400,) for image data when plotting a simpleitk image with imshow


I am trying to display an image with imshow which is read with simpleItk. Image details are as follows:

size = fusedImage.GetSize()
(120, 120, 155)

type(fusedImage)
SimpleITK.SimpleITK.Image

im = fusedImage[:,:,76]
im.GetSize()
(120,120)

plt.imshow(im) 

But I get the following error: TypeError: Invalid shape (14400,) for image data

Can someone please tell me what I am doing wrong here?


Solution

  • SimpleITK.Image is technically array-like but NumPy can't tell what shape it is. Thankfully the library offers a way to make a NumPy array that views the image data:

    im_view = SimpleITK.GetArrayViewFromImage(im)
    plt.imshow(im_view)
    

    Couple notes: 1) indexing is in opposite order so im[x,y] == im_view[y,x], 2) you can't use a NumPy view-array to mutate the image, 3) use GetArrayFromImage instead if you want to make a NumPy array of a separate copy of the data.