我有5张图片,想将每张图片转换为一维数组,并将其作为向量放入矩阵中。
我希望能够再次将每个向量转换为图片。
img = Image.open('orig.png').convert('RGBA')
a = np.array(img)
我对numpy的所有功能都不熟悉,想知道是否有其他工具可供使用。
谢谢。
我有5张图片,想将每张图片转换为一维数组,并将其作为向量放入矩阵中。
我希望能够再次将每个向量转换为图片。
img = Image.open('orig.png').convert('RGBA')
a = np.array(img)
我对numpy的所有功能都不熟悉,想知道是否有其他工具可供使用。
谢谢。
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)
img.shape
返回一个元组,通过上述的多重赋值给 rows,cols,colors
,我们可以计算转换为和从一维向量中所需的元素数量。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 =数据类型);每个似乎都可以正常工作。
希望这有所帮助。
我曾经使用以下代码将二维图像数组转换为一维:
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);
from PIL import Image
。如果您没有安装PIL,请考虑安装Pillow,这是PIL的一个积极开发的分支。 - unutbu