Python绘图中YaleB_32x32数据集图像显示旋转的问题排查求助
Hey there! I see exactly why your images are turning out rotated—it all comes down to how Matlab vs. Python handle array reshaping order. Let’s break this down and fix it for you.
The Root Cause
The YaleB_32x32.mat dataset is stored in Matlab's column-major (Fortran-style) order. That means when the 2D images were flattened into 1D vectors, they were read column by column. But Python’s reshape() uses row-major (C-style) order by default. This mismatch flips the orientation of your images when you reshape them back to 32x32.
Quick Fixes for Your Code
You have two simple, effective ways to correct this:
1. Transpose the reshaped array
After reshaping to 32x32, add a transpose .T to flip the axes back to their original orientation:
vecX = matX[i,:].reshape(32,32).T # Transpose to fix rotation
2. Use column-major order in reshape
Specify order='F' (Fortran-style) directly in the reshape() call to match how the data was stored in the Matlab file:
vecX = matX[i,:].reshape(32,32, order='F') # Reshape using column-major order
Updated Full Code
Here’s your code with the first fix applied (either option works perfectly):
import scipy.io import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec imgData = scipy.io.loadmat('/path/YaleB_32x32.mat') matX = imgData['fea'] plt.figure(figsize = (6,6)) gs1 = gridspec.GridSpec(6, 6) gs1.update(wspace=0.01, hspace=0.01) for i in range(36): vecX = matX[i,:].reshape(32,32).T # Fixed line ax1 = plt.subplot(gs1[i]) plt.imshow(vecX, cmap = 'gray') plt.axis('off') plt.show() # Don't forget to render the final plot!
Why This Works
By either transposing the array or using Fortran-style reshaping, you’re aligning the 1D vector back into the original 2D image structure that matches how the data was captured and stored in the Matlab file. Your images should now display in the correct orientation.
内容的提问来源于stack exchange,提问作者BitastaB

