为了加深理解,写了一些代码测试,在这里记录一下吧:
关于图片的模式问题,之前做过笔记,有“1”,“L”,"P","RGB","RGBA","CMYK',"YCBCr","Note","LAB"等,这几种图片模式有什么区别呢?
#001
from PIL import Image
img1=Image.new("1",(3,3))
data1=img1.getdata()
print(list(data1))
img2=Image.new("L",(3,3))
data2=img2.getdata()
print(list(data2))
img3=Image.new("P",(3,3))
data3=img3.getdata()
print(list(data3))
img4=Image.new("RGB",(3,3))
data4=img4.getdata()
print(list(data4))
img5=Image.new("CMYK",(3,3))
data5=img5.getdata()
print(list(data5))
>>
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)]
[(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0)]
可以看出"1","L",“P”模式都是用一位表示颜色值,而"RGB'使用3位表示颜色值,"RGBA","CMYK"等用四位来表示
#002
from PIL import Image img1=Image.new("1",(3,3),18) data1=img1.getdata() print(list(data1)) img1.save("2.png") img_1=Image.open("2.png") print(list(img_1.getdata()))
>>
[18, 18, 18, 18, 18, 18, 18, 18, 18]
[255, 255, 255, 255, 255, 255, 255, 255, 255]
之前说"1"模式只有黑白两种颜色,一个像素也是用一位表示,那试着在创建它的时候给它设置一个非黑白色的颜色,结果保存再读取出来的,又自动变成黑色了
#003
from PIL import Image img1=Image.new("L",(3,3),(30,30,30)) data1=img1.getdata() print(list(data1))
>>TypeError: function takes exactly 1 argument (3 given)
#004
from PIL import Image img1=Image.new("RGB",(3,3),(30,30,30)) data1=img1.getdata() print(list(data1)) img1.save("2.png") img_1=Image.open("2.png") print(list(img_1.getdata()))
>>
[(30, 30, 30), (30, 30, 30), (30, 30, 30), (30, 30, 30), (30, 30, 30), (30, 30, 30), (30, 30, 30), (30, 30, 30), (30, 30, 30)]
[(30, 30, 30), (30, 30, 30), (30, 30, 30), (30, 30, 30), (30, 30, 30), (30, 30, 30), (30, 30, 30), (30, 30, 30), (30, 30, 30)]
创建“L”模式时,给它传入一个rgb值报错了,“RGB”模式则可以。
然后,对于RGB模式去亮色转灰色有点好奇,在网上找到很多方法,不明所以,但是有几个公式可以用,其中一个是:
gray=R*0.3+G*0.59+B*0.11,顺便试了一下
#005
from PIL import Image img1=Image.new("RGB",(100,100),(135,206,235)) #img1.show() gray=135*0.3+206*0.59+235*0.11 img2=Image.new("RGB",(100,100),(int(gray),int(gray),int(gray))) print(str(gray)) print(str(int(gray))) img2.show()
#006
from PIL import Image img1=Image.open("f:\cat.jpg") or_data=list(img1.getdata()) #print(or_data) gr_data=[] for pix in or_data: i=pix[0]*0.3+pix[1]*0.59+pix[2]*0.11 j=int(i) gr_pix=(j,j,j) gr_data.append(gr_pix) gr_img=Image.new("RGB",(img1.size[0],img1.size[1])) gr_img.putdata(gr_data) gr_img.show()
转化效果