PIL模塊-用與記
- 1.圖片導入Image.open()
- 2.圖像顯示.show()
- 4.查看圖片屬性.format,.size,.mode
- 3.圖像格式轉換.convert()
- 4.圖像模式“L”,“RGB”,"CYMK"
- 5. 圖片旋轉.rotate()
- 旋轉方式1:旋轉不擴展
- 旋轉方式2:旋轉擴展
- 旋轉方式3:旋轉,擴展,白色填充
- 6.圖片切割.crop()
- 7.圖片保存.save()
PIL:Python Imaging Library,為Python圖像處理常用的庫。
PIL手冊網站:http://effbot.org/imagingbook/pil-index.htm
PIL庫中最重要的一個類:Image,可以通過這個類/模塊 導入圖像,處理圖像,保存圖像
import Image
1.圖片導入Image.open()
img=Image.open(“xxx/xxx/lena.jpg”)
導入路徑中的文件名后要帶擴展名,不然會報一下錯誤:
IOError: [Errno 2] No such file or directory: ‘lena’
2.圖像顯示.show()
img.show()
4.查看圖片屬性.format,.size,.mode
圖片源格式,圖片尺寸,圖片模式
print(img.format , img.size , img.mode)
輸出
(‘JPEG’, (200, 200), ‘RGB’)
3.圖像格式轉換.convert()
img.convert('L")
img.show()
mode 從"RGB" 轉變成"L"
4.圖像模式“L”,“RGB”,“CYMK”
PIL中的圖像有一下9種模式,使用.convert()函數,可以讓圖片在這9中模式中來回轉換。(作為參數,模式要加引號)
· 1 (1-bit pixels, black and white, stored with one pixel per byte)
· L (8-bit pixels, black and white) # 灰度
· P (8-bit pixels, mapped to any other mode using a colour palette)
· RGB (3x8-bit pixels, true colour) # 彩色
· RGBA (4x8-bit pixels, true colour with transparency mask)
· CMYK (4x8-bit pixels, colour separation)
· YCbCr (3x8-bit pixels, colour video format)
· I (32-bit signed integer pixels)
· F (32-bit floating point pixels)
參考資料:https://www.cnblogs.com/shangpolu/p/8041848.html
5. 圖片旋轉.rotate()
旋轉方式1:旋轉不擴展
#在原圖上旋轉,旋轉后的圖像與原圖大小一致,轉出圖像的部分會被丟棄,所以會造成信息丟失
img2=img.rotate(45)
旋轉方式2:旋轉擴展
#旋轉后擴展,信息不丟失,圖像尺寸變大
img3=img.rotate(45,expand=True)
)
旋轉方式3:旋轉,擴展,白色填充
img_alpha=img.convert("RGBA") # 將原圖轉換成RGBA的格式,四個通道,另一個通道表示透明度,默認為255,完全不透明
rot = img_alpha.rotate(45, expand = True) # 旋轉圖片fff=Image.new("RGBA",rot.size,(255,255,255,255))
out=Image.composite(rot,fff,mask=rot)
out.convert(img.mode).show()
# RGBA模式需要轉換成RGB,才能存儲,不然會報錯
參考資料:https://blog.csdn.net/luolinll1212/article/details/83059118
6.圖片切割.crop()
box = (0, 0, 100, 150) #切割區域的四個坐標(left,top,right,bottom)
region = img.crop(box)
PIL 圖像坐標系以圖像的左上角為(0,0)位置,第一維度為長,第二維度為高。
7.圖片保存.save()
img.save("…/testdir/img.jpg")
如果文件目錄不存在,就會報錯
FileNotFoundError: [Errno 2] No such file or directory: ‘…/testdir/img.jpg’