Search code examples
pythonmatlabnumpymatplotlibtheano

Why does matplotlib imshow() display a transposed image?


I have an matrix of images created in matlab which i will be using as an input to a convolutional neural network i am coding in theano. I've imported the matrix using numpy.loadtxt and on inspection the matrix appears identical to the one created in matlab. When using imshow() in matlab i get the images displayed corrected, however, when using matplotlib imshow() the images are transposed. Does anyone know the cause of this?

Code for matlab:

    img = dlmread('kthImagesCheck.txt');
    imshow(reshape(img(:,1), [104,104]))

Code for matplotlib:

    img = numpy.loadtxt("kthImagesCheck", delimiter = ",")
    imshow(reshape(img[:,0],[104,104])

I would post the images but im new to stackoverflow and i don't have enough reputation yet.

Cheers,


Solution

  • Matlab and python has a different way to store arrays in memory. Matlab saves an array column-first, while python uses row-first method.
    Consider, for example, a 2-by-2 matrix

    M = [1, 2
         3, 4]
    

    In memory, matlab save the matrix as [1 3 2 4] while python's order is [1 2 3 4]. This effect causes your image to be transposed.

    Consider transposing the images in Matlab prior to saving them - this way the data is stored in memory in the same order as in python.