#https://*.com/questions/384759/how-to-convert-a-pil-image-into-a-numpy-array from PIL import Image
import numpy as np
img1=Image.open("f:\cat.jpg")
pix_data2=np.array(img1.getdata()).reshape(img1.size[0],img1.size[1],3)
im=Image.fromarray(np.uint8(pix_data2)) im.show()
这个程序的有意思之处在于把rgb图的通道,分开存入一个三维数组的三个维度中,可以加深对图片通道的理解,比如把程序修改成
from PIL import Image
import numpy as np
img1=Image.open("f:\cat.jpg") pix_data2=np.array(img1.getdata()).reshape(img1.size[0],img1.size[1],3) pix_data4=pix_data2[0:,0:,0:1]
pix_data5=pix_data2[0:,0:,1:2]
pix_data6=pix_data2[0:,0:,2:3]
pix_data7=pix_data2[0:,0:,0:2]
pix_data8=pix_data2[0:,0:,1:3]
pix_data9=pix_data2[0:,0:,::2] print(list(pix_data2))
print(list(pix_data4))
print(list(pix_data5))
print(list(pix_data6))
print(list(pix_data6))
print(list(pix_data7))
Image.fromarray(np.uint8(pix_data7)).show()
Image.fromarray(np.uint8(pix_data8)).show()
Image.fromarray(np.uint8(pix_data9)).show()
>>
rgb三色去掉一种颜色就变成灰色,另外把颜色rgb颜色反转(r<-b,g<-g,b<-r)也产生让人意想不到的效果