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

十年热恋 提交于 2021-01-20 18:08:33

问题



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.png').convert('RGBA')
a = np.array(img)

I'm not familiar with all the features of numpy and wondered if there other tools I can use.
Thanks.


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



回答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.




回答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



来源:https://stackoverflow.com/questions/15612373/convert-image-png-to-matrix-and-then-to-1d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!