Home > Enterprise >  Why matplotlib imshow shows different images by changing the order of the array?
Why matplotlib imshow shows different images by changing the order of the array?

Time:05-19

I have a test case that reshaping the array changes the result of plt.imshow:

import numpy as np
import matplotlib.pyplot as plt
from skimage import io

file_raw_path = "8258792/Fig5_ColorfulCell_raw.tif"

im = io.imread(file_raw_path)

im= np.max(im, axis=0)

im_reshaped = im.reshape((im.shape[1],im.shape[2],im.shape[0]))

for i in range(im.shape[0]):
    plt.imshow(im[i],cmap='gray')
    plt.show()

for i in range(im_reshaped.shape[2]):
    plt.imshow(im_reshaped[...,i],cmap='gray')
    plt.show()

The first loop shows these images:

enter image description here enter image description here enter image description here enter image description here enter image description here

And the second loop shows this image (of course 5 times the same thing...):

enter image description here

Any idea why this is happening?!

CodePudding user response:

np.reshape() doesn't move any data around; it just changes where the axes "wrap around". You can think about it as first flattening the input array, then wrapping the data across the axes to fit the new shape.

>>> arr = np.arange(6).reshape(2, 3)
array([[0, 1, 2],
       [3, 4, 5]])
>>> arr.reshape(3, 2)
array([[0, 1],
       [2, 3],
       [4, 5]])
>>> arr.

If you read across left-to-right, top-to-bottom, all the numbers are in the same order.

You probably want np.transpose() and friends, which (essentially) shuffle the data around to change the order of the axes, so that im[i, j, k] == im.transpose(1, 2, 0)[j, k, i] (note, it doesn't actually move any data, it just looks like that). For your use case, np.moveaxis(im, 0, -1) will do the same thing, and is a bit easier to read ("move axis 0 to the end").

>>> arr.transpose(1, 0)
array([[0, 3],
       [1, 4],
       [2, 5]])
  • Related