Convert image (png) to a matrix and then to a 1D array


I have 5 photos and I want to convert each image into a 1d array and put it in a matrix as a vector.
I want to be able to convert each vector into an image again.

img = Image.open('orig.png').convert('RGBA')
a = np.array(img)

I am not familiar with all the numpy functions and am wondering if there are other tools that I can use.
Thank.

+5
source share
3 answers
import numpy as np
from PIL import Image

img = Image.open('orig.png').convert('RGBA')
arr = np.array(img)

# record the original shape
shape = arr.shape

# make a 1-dimensional view of arr
flat_arr = arr.ravel()

# convert it to a matrix
vector = np.matrix(flat_arr)

# do something to the vector
vector[:,::10] = 128

# reform a numpy array of the original shape
arr2 = np.asarray(vector).reshape(shape)

# make a PIL image
img2 = Image.fromarray(arr2, 'RGBA')
img2.show()
+18
source
import matplotlib.pyplot as plt

img = plt.imread('orig.png')
rows,cols,colors = img.shape # gives dimensions for RGB array
img_size = rows*cols*colors
img_1D_vector = img.reshape(img_size)
# you can recover the orginal image with:
img2 = img_1D_vector.reshape(rows,cols,colors)

Note that the img.shapetuple returns, and the multiple assignment rows,cols,colorsas described above allows you to calculate the number of elements needed to convert to and from a 1D vector.

img img2, :

plt.imshow(img) # followed by 
plt.show() # to show the first image, then 
plt.imshow(img2) # followed by
plt.show() # to show you the second image.

, python plt.show() , .

matplotlib.pyplot. jpg tif .. png , float32 dtype, jpg tif, , uint8 dtype (dtype = ); , , .

, .

+2

I used to convert a 2D-1D array of images using this code:

import numpy as np
from scipy import misc
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt

face = misc.imread('face1.jpg');
f=misc.face(gray=True)
[width1,height1]=[f.shape[0],f.shape[1]]
f2=f.reshape(width1*height1);

but I still don't know how to change it to 2D later in the code. Also note that not all imported libraries are needed, I hope this helps

+1
source

All Articles