1. 程式人生 > >Python之PIL圖片操作

Python之PIL圖片操作

參考:https://www.cnblogs.com/meitian/p/3699223.html

之前一直是用opencv對圖片進行讀取、顯示等操作,後來發現Python自帶的庫PIL也可以完成相同的操作,至於兩者的區別,後邊再研究,本文總結PIL常用的方法函式。在使用之前,要先匯入庫

from PIL import Image

1 開啟圖片

img=Image.open("kobe.jpg")

注:有些圖片名稱是包含中文的,就需要在“”前加上u,例:img=Image.open(u"阿布.jpg")

2 顯示圖片

img.show()

3 輸出圖片資訊

print img.mode,img.size,img.format

結果為 RGB (508, 493) JPEG

4 儲存圖片

img.save("img1.png","png")

說明:img為一個圖片,存為一個名叫img1的圖片,格式為png。後面的png不寫也可以,直接按照檔名的字尾.png存為相應格式了。

5 改變圖片尺寸

smallimg=img.resize((128,128),Image.ANTIALIAS)

說明:(128,128)為更改後的尺寸,Image.ANTIALIAS有消除鋸齒的效果。

6 圖片型別轉化

img=img.convert("RGBA")

說明:將img圖片的mode轉換為"RGBA"格式

7 分割通道

bands=img.split()
rIm=bands[0]
gIm=bands[1]
bIm=bands[2]
aIm=bands[3]

說明:將img代表的圖片分割通道。

如果是RGBA,分割後就有四個通道。bands[0]、bands[1]、bands[2]、bands[3]分別代表了R(red)、G(green)、B(blue)、A(alpha)四個通道。

8 合併通道

img=img.convert("RGBA")
bands=img.split()
rIm=bands[0]
gIm=bands[1]
bIm=bands[2]
aIm=bands[3]
remadeImage=Image.merge("RGBA",(rIm,gIm,bIm,aIm))
remadeImage.save("remadeImage.png","png")

說明:使用Image.merge("RGBA",(rIm,gIm,bIm,aIm))將通道合成為一個圖片,"RGBA"格式的圖片通道分為R(red)、G(green)、B(blue)、A(alpha)。rIm,gIm,bIm,aIm分別為自定義的R、G、B、A。

9 貼上圖片

import Image
img=Image.open(u"阿布.jpg")
img1=Image.open("code.jpg")
img.paste(img1,(0,10))img.save("img2.png")

說明:img.paster(img1,(0,10)是將圖片img1貼上到圖片img上。(0,10)是貼上的座標位置。

10 拷貝圖片

img=Image.open(u"阿布.jpg")
bounds=(0,0,493,254)
cutoutIm=img.crop(bounds)
cutoutIm.save("cotoutIm.png","png")

說明:bounds為自定義的拷貝區域(x1,y1,x2,y2),x1和y1決定了拷貝區域左上角的位置,x2和y2決定了拷貝區域右下角的位置。

img.crop(bounds):拷貝圖片img座標區域在bounds之間的圖片。

11 旋轉圖片

fixedIm=img.rotate(90)
fixedIm.save("fixedIm.png","png")

說明:fixedIm=img.rotate(90),將圖片img逆時針旋轉90度,存到fixedIm中。

12 對畫素進行操作

img=Image.open("smallimg.png")
img.getpixel((4,4))
img.putpixel((4,4),(255,0,0))
img.save("img1.png","png")

說明:getpixel得到圖片img的座標為(4,4)的畫素點。putpixel將座標為(4,4)的畫素點變為(255,0,0)顏色,即紅色。

13 使用ImageDraw庫進行畫圖

import ImageDraw

img=Image.open(u'阿布.jpg')
a=ImageDraw.Draw(img)
a.line(((0,0),(508,493)),fill=(255,0,0))
a.line(((0,493),(508,0)),fill=(0,255,0,0))
a.arc((10,10,100,100),0,360,fill=255)
#因為PIL庫編譯時缺少東西,所以導致字型不能更改
#font = ImageFont.truetype ("Arial.ttf",16)
a.text((10,10),"hello",fill=(255,0,0),font=None)
img.save("img1.png")

說明:1.畫圖需要匯入ImageDraw庫。

   2.a=ImageDraw.Draw(img),對img影象進行畫圖操作

   3.a.line,畫直線。((0,0),(508,493))為直線左右起點的座標。fill=(255,0,0)為直線填充的顏色。

   4.a.arc,畫弧線。(10,20,100,300)為弧線最左側距離左邊、弧線最上面距離上面、弧線最右面距離左面、弧線最下面距離左邊的距離。fill=255為填充的顏色,也可以寫成(255,0,0,0)的格式。

   5.a.text為新增文字,(10,10)為新增文字的位置,fill=(255,0,0)為填充文字的顏色,font為文字的字型,None為沒有樣式,font可以自定義。自定義方法為font = ImageFont.truetype ("Arial.ttf",16)