简体   繁体   English

将图像(png)转换为矩阵,然后转换为1D阵列

[英]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. 我有5张图片,我想将每个图像转换为1d数组,并将其作为矢量放在矩阵中。
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. 我不熟悉numpy的所有功能,并想知道我是否可以使用其他工具。
Thanks. 谢谢。

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()
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. 请注意, img.shape返回一个元组,如上所述对rows,cols,colors多个赋值让我们计算转换为1D向量和从1D向量转换所需的元素数。

You can show img and img2 to see they are the same with: 您可以显示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.

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. 请记住,在python终端中,您必须关闭plt.show()窗口才能返回到终端以显示下一个图像。

For me it makes sense and only relies on matplotlib.pyplot. 对我来说这是有道理的,只依赖于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); 它也适用于jpg和tif图像等。我试过它的png有float32 dtype和jpg和tif我试过它有uint8 dtype(dtype = data type); each seems to work. 每个似乎都有效。

I hope this is helpful. 我希望这是有帮助的。

I used to convert 2D to 1D image-array using this code: 我曾经使用以下代码将2D转换为1D图像数组:

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 但我还不知道如何在代码中将其更改回2D,还要注意并非所有导入的库都是必需的,我希望它有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM