Skip to content Skip to sidebar Skip to footer

Convert Image ( Png ) To Matrix And Then To 1D Array

I have 5 pictures and i want to convert each image to 1d array and put it in a matrix as vector. I want to be able to convert each vector to image again. img = Image.open('orig.pn

Solution 1:

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()

Solution 2:

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 img.shape returns a tuple, and multiple assignment to rows,cols,colors as above lets us compute the number of elements needed to convert to and from a 1D vector.

You can show img and img2 to see they are the same with:

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.

Keep in mind in the python terminal you have to close the plt.show() window to come back to the terminal to show the next image.

For me it makes sense and only relies on matplotlib.pyplot. It also works for jpg and tif images, etc. The png I tried it on has float32 dtype and the jpg and tif I tried it on have uint8 dtype (dtype = data type); each seems to work.

I hope this is helpful.


Solution 3:

I used to convert 2D to 1D image-array 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 don't know yet how to change it back to 2D later in code, Also note that not all the imported libraries are necessary, I hope it helps


Post a Comment for "Convert Image ( Png ) To Matrix And Then To 1D Array"