如何旋转矩阵图像以得到直立状态的数字5?
I get it—trying to get that digit 5 to show up upright can be tricky with R's image() function, since it plots matrices in a way that's counterintuitive for images. Let's break down why your initial attempts didn't work and how to fix it.
Why Your Current Code Isn't Working
The image() function in R renders matrices with rows starting at the bottom (opposite of how we typically view images). Transposing the matrix swaps rows and columns, but it doesn't fix the vertical flip or horizontal mirroring that's keeping your 5 from looking right.
Solution 1: Transpose + Reverse Columns
This is a straightforward fix. After transposing the matrix, reverse the order of the columns to flip the image horizontally and get the upright digit:
# Create the original 28x28 matrix from your data digit_matrix <- matrix(data[, 11552], nrow = 28, byrow = TRUE) # Transpose and reverse columns to get the correct orientation image(t(digit_matrix)[, ncol(digit_matrix):1], col = gray(0:255/255))
Solution 2: Reverse Rows First, Then Transpose
Another approach is to flip the matrix vertically first (by reversing the rows) before transposing. This also results in an upright 5:
digit_matrix <- matrix(data[, 11552], nrow = 28, byrow = TRUE) # Reverse rows to fix vertical flip, then transpose image(t(digit_matrix[rev(seq(nrow(digit_matrix))), ]), col = gray(0:255/255))
Bonus: Clean Up the Plot
If you want to remove the axes and focus solely on the digit, add axes = FALSE to the image() call:
image(t(digit_matrix)[, ncol(digit_matrix):1], col = gray(0:255/255), axes = FALSE)
Either of these methods should give you the upright number 5 you're looking for!
内容的提问来源于stack exchange,提问作者Jatt

