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

时间:2013-03-25 10:12:44

标签: python image-processing numpy


我有5张图片,我想将每个图像转换为1d数组并将其作为矢量放入矩阵。
我希望能够将每个矢量再次转换为图像。

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

我不熟悉numpy的所有功能,并想知道我是否还可以使用其他工具。
感谢。

3 个答案:

答案 0 :(得分:20)

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

答案 1 :(得分:3)

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)

请注意,img.shape返回一个元组,如上所述,对rows,cols,colors的多次赋值使我们能够计算在1D向量之间进行转换所需的元素数。

您可以显示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 :(得分:1)

我曾经使用以下代码将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);

但我还不知道如何在代码中将其更改回2D,另请注意,并非所有导入的库都是必需的,我希望它有所帮助

相关问题