Numpy reshape RGB image to 1D array
Description of this Notebook
Quick Links
Imagine you want to train a NN with:
Where:
- s: num samples
- 3 x 32 x 32: color img
Now to feed in the NN we want the shapes to be:
Do we lose information? The answers is not, we just reshape X.
The following takes 2 imgs, with dimensions 2x2:
import numpy as np
# Create example 3x2x2 images (two images)
original_images = np.array([[[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]],
[[9, 10],
[11, 12]]],
[[[13, 14],
[15, 16]],
[[17, 18],
[19, 20]],
[[21, 22],
[23, 24]]]])
# Print the shape of the original images
print("Original Images Shape:", original_images.shape)
# Print the original images
print("Original Images:\n", original_images)
# Reshape the images into num_imgs x (3*2*2) matrices
num_imgs = original_images.shape[0]
reshaped_images = original_images.reshape(num_imgs, -1)
# Print the shape of the reshaped images
print("Reshaped Images Shape:", reshaped_images.shape)
# Print the reshaped images
print("Reshaped Images:\n", reshaped_images)
Original Images Shape: (2, 3, 2, 2)
Original Images:
[[[[ 1 2]
[ 3 4]]
[[ 5 6]
[ 7 8]]
[[ 9 10]
[11 12]]]
[[[13 14]
[15 16]]
[[17 18]
[19 20]]
[[21 22]
[23 24]]]]
Reshaped Images Shape: (2, 12)
Reshaped Images:
[[ 1 2 3 4 5 6 7 8 9 10 11 12]
[13 14 15 16 17 18 19 20 21 22 23 24]]