最近工作中需要用到圖片的自動化處理,于是了解了一下PIL程序庫新荤。
什么是PIL
PIL(Python Imaging Library)是python中處理圖像常用的一個庫揽趾,常見的用法包括可以操作二維像素點、線苛骨、文字以及對現(xiàn)有圖片的縮放篱瞎、變形、通道處理智袭,也可以轉換圖片的編碼格式奔缠,可以比較兩幅圖片的不同。
安裝
python中安裝庫一般通過pip或者easy_install吼野,如果這兩者不可行,一般在搜索引擎找到官網(wǎng)或者github項目地址两波,進入主目錄執(zhí)行python setup.py install瞳步。PIL安裝方式亦如上所述闷哆。
使用場景
基本操作:打開,打印文件屬性和展示圖片
>>> import Image
>>> im = Image.open("lena.ppm")
>>> print im.format, im.size, im.mode
PPM (512, 512) RGB
>>> im.show()
其中format包括jpg,png,gif,bmp等
size很好理解单起,返回的是一個二元組代表寬高
mode代表的是色彩模式抱怔,除了RGB,共支持如下模式
- 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)
圖片縮放:
size = (128, 128)
im = Image.open(infile)
im.thumbnail(size)
經(jīng)過測試嘀倒,縮放是會保留原始長寬比的屈留,縮放操作其實意味著在保留長寬比的前提下,縮放后結果的高不大于128,寬也不大于128.
縮放時還有一個filter參數(shù)测蘑,可以控制圖片的質量灌危,壓縮時PIL處理過程中稱為resampling的過程,可以采用以下filter:
- NEAREST
Pick the nearest pixel from the input image. Ignore all other input pixels.
直接采用該像素點最近的像素點的色彩值
- BILINEAR
Use linear interpolation over a 2x2 environment in the input image. Note that in the current version of PIL, this filter uses a fixed input environment when downsampling.
類似第一種碳胳,只不過擴大了采樣的范圍并作平均勇蝙。是2*2的范圍
- BICUBIC
Use cubic interpolation over a 4x4 environment in the input image. Note that in the current version of PIL, this filter uses a fixed input environment when downsampling.
進一步擴大到了4*4的范圍
- ANTIALIAS
(New in PIL 1.1.3). Calculate the output pixel value using a high-quality resampling filter (a truncated sinc) on all pixels that may contribute to the output value. In the current version of PIL, this filter can only be used with the resize and thumbnail methods.
看不太懂,反正這個是推薦的挨约,官方認為只要不是對速度有非常大的要求味混,都要采用這個filter。
通過實際操作诫惭,確實發(fā)現(xiàn)第四種明顯減少了鋸齒翁锡,而第一種nearest鋸齒最為嚴重
圖片轉換:
im = Image.open(“a.png")
im.save(“a.jpg”)
PIL默認會讀取后綴名來應該用何種編碼來轉換這張圖片。
圖片粘貼:
width = 850
height = 510
im = Image.open(“for_paste.jpg")
image = Image.new('RGB', (width, height), (255, 255, 255))
box = (250,42,550,325)
image.paste(im,box)
代碼首先新建了一個image對象夕土,作為我們的畫布馆衔,然后將for_paster.jpg粘貼到畫面中的區(qū)域。box是一個四元組隘弊,含義為(左上角x哈踱,左上角y,右下角x梨熙,右下角y)开镣。這里如果box的寬和高與被粘貼圖片的寬高不一致,系統(tǒng)會拋異常咽扇。
圖片中寫字:
#創(chuàng)建一個字體實例邪财,采用微軟雅黑38號
font_en = ImageFont.truetype('/Library/Fonts/Microsoft/Microsoft Yahei.ttf',38)
draw = ImageDraw.Draw(image)
#指定字體和顏色(RGB)
draw.text( (0,100), u’He acknowledged his faults.', font=font_en,fill=(0,0,0))
del draw
結果如下: