需求:将我本地任意张图片转换为向量形式
girl.jpg
import numpy as np
from PIL import Image
img = Image.open('girl.jpg').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 = Image.fromarray(arr2 * 3, 'RGBA')
# print(246 * 3 - 256 * 2) # 超过255会自动减去256
img2.show()
img2.save('out.png') # 保存图片
arr2
arr2为图片的向量形式
array([[[128, 182, 175, 255],
[167, 182, 175, 255],
[167, 182, 128, 255],
...,
[166, 183, 128, 255],
[166, 183, 177, 255],
[166, 183, 177, 255]],
[[128, 182, 175, 255],
[167, 182, 175, 255],
[167, 182, 128, 255],
...,
[166, 183, 128, 255],
[166, 183, 177, 255],
[166, 183, 177, 255]],
[[128, 181, 174, 255],
[166, 181, 176, 255],
[166, 181, 128, 255],
...,
[166, 183, 128, 255],
[166, 183, 177, 255],
[166, 183, 177, 255]],
...,
[[128, 73, 80, 255],
[ 96, 75, 82, 255],
[ 98, 77, 128, 255],
...,
[ 67, 77, 128, 255],
[ 64, 77, 86, 255],
[ 64, 77, 86, 255]],
[[128, 59, 66, 255],
[ 83, 62, 69, 255],
[ 85, 64, 128, 255],
...,
[ 66, 76, 128, 255],
[ 64, 77, 86, 255],
[ 64, 77, 86, 255]],
[[128, 53, 60, 255],
[ 76, 55, 62, 255],
[ 78, 57, 128, 255],
...,
[ 65, 75, 128, 255],
[ 64, 77, 86, 255],
[ 64, 77, 86, 255]]], dtype=uint8)
out.jpg