Python模块(3)--PIL 简易使用教程
PIL模塊-用與記
- 1.圖片導(dǎo)入Image.open()
- 2.圖像顯示.show()
- 4.查看圖片屬性.format,.size,.mode
- 3.圖像格式轉(zhuǎn)換.convert()
- 4.圖像模式“L”,“RGB”,"CYMK"
- 5. 圖片旋轉(zhuǎn).rotate()
- 旋轉(zhuǎn)方式1:旋轉(zhuǎn)不擴(kuò)展
- 旋轉(zhuǎn)方式2:旋轉(zhuǎn)擴(kuò)展
- 旋轉(zhuǎn)方式3:旋轉(zhuǎn),擴(kuò)展,白色填充
- 6.圖片切割.crop()
- 7.圖片保存.save()
PIL:Python Imaging Library,為Python圖像處理常用的庫(kù)。
PIL手冊(cè)網(wǎng)站:http://effbot.org/imagingbook/pil-index.htm
PIL庫(kù)中最重要的一個(gè)類(lèi):Image,可以通過(guò)這個(gè)類(lèi)/模塊 導(dǎo)入圖像,處理圖像,保存圖像
import Image
1.圖片導(dǎo)入Image.open()
img=Image.open(“xxx/xxx/lena.jpg”)
導(dǎo)入路徑中的文件名后要帶擴(kuò)展名,不然會(huì)報(bào)一下錯(cuò)誤:
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.圖像格式轉(zhuǎn)換.convert()
img.convert('L")
img.show()
mode 從"RGB" 轉(zhuǎn)變成"L"
4.圖像模式“L”,“RGB”,“CYMK”
PIL中的圖像有一下9種模式,使用.convert()函數(shù),可以讓圖片在這9中模式中來(lái)回轉(zhuǎn)換。(作為參數(shù),模式要加引號(hào))
· 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. 圖片旋轉(zhuǎn).rotate()
旋轉(zhuǎn)方式1:旋轉(zhuǎn)不擴(kuò)展
#在原圖上旋轉(zhuǎn),旋轉(zhuǎn)后的圖像與原圖大小一致,轉(zhuǎn)出圖像的部分會(huì)被丟棄,所以會(huì)造成信息丟失 img2=img.rotate(45)旋轉(zhuǎn)方式2:旋轉(zhuǎn)擴(kuò)展
#旋轉(zhuǎn)后擴(kuò)展,信息不丟失,圖像尺寸變大 img3=img.rotate(45,expand=True))
旋轉(zhuǎn)方式3:旋轉(zhuǎn),擴(kuò)展,白色填充
img_alpha=img.convert("RGBA") # 將原圖轉(zhuǎn)換成RGBA的格式,四個(gè)通道,另一個(gè)通道表示透明度,默認(rèn)為255,完全不透明 rot = img_alpha.rotate(45, expand = True) # 旋轉(zhuǎn)圖片fff=Image.new("RGBA",rot.size,(255,255,255,255)) out=Image.composite(rot,fff,mask=rot) out.convert(img.mode).show() # RGBA模式需要轉(zhuǎn)換成RGB,才能存儲(chǔ),不然會(huì)報(bào)錯(cuò)參考資料:https://blog.csdn.net/luolinll1212/article/details/83059118
6.圖片切割.crop()
box = (0, 0, 100, 150) #切割區(qū)域的四個(gè)坐標(biāo)(left,top,right,bottom) region = img.crop(box)PIL 圖像坐標(biāo)系以圖像的左上角為(0,0)位置,第一維度為長(zhǎng),第二維度為高。
7.圖片保存.save()
img.save("…/testdir/img.jpg")
如果文件目錄不存在,就會(huì)報(bào)錯(cuò)
FileNotFoundError: [Errno 2] No such file or directory: ‘…/testdir/img.jpg’
總結(jié)
以上是生活随笔為你收集整理的Python模块(3)--PIL 简易使用教程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: pySerial -- Python的串
- 下一篇: NLP复习资料(4)-第八章 句法分析