Python編程中使用Pillow來處理圖像的基礎(chǔ)教程
安裝
剛接觸Pillow的朋友先來看一下Pillow的安裝方法,在這里我們以Mac OS環(huán)境為例:
(1)、使用 pip 安裝 Python 庫。pip 是 Python 的包管理工具,安裝后就可以直接在命令行一站式地安裝/管理各種庫了(pip 文檔)。
$ wget http://pypi.python.org/packages/source/p/pip/pip-0.7.2.tar.gz $ tar xzf pip-0.7.2.tar.gz $ cd pip-0.7.2 $ python setup.py install
(2)、使用 pip 下載獲取 Pillow:
$ pip install pillow
(3)、安裝過程中命令行出現(xiàn)錯誤提示:”error: command ‘clang' failed with exit status 1”。上網(wǎng)查閱,發(fā)現(xiàn)需要通過 Xcode 更新 Command Line Tool。于是打開 Xcode->Preferences->Downloads-Components選項卡。咦?竟然沒了 Command Line Tools。再查,發(fā)現(xiàn) Xcode 5 以上現(xiàn)在需要用命令行安裝:
$ xcode-select —install
系統(tǒng)會彈出安裝命令行工具的提示,點(diǎn)擊安裝即可。
此時再 pip install pillow,就安裝成功了。
pip freeze 命令查看已經(jīng)安裝的 Python 包,Pillow 已經(jīng)乖乖躺那兒了。
好了,下面開始進(jìn)入教程~
Image類
Pillow中最重要的類就是Image,該類存在于同名的模塊中??梢酝ㄟ^以下幾種方式實例化:從文件中讀取圖片,處理其他圖片得到,或者直接創(chuàng)建一個圖片。
使用Image模塊中的open函數(shù)打開一張圖片:
>>> from PIL import Image >>> im = Image.open("lena.ppm")
如果打開成功,返回一個Image對象,可以通過對象屬性檢查文件內(nèi)容
>>> from __future__ import print_function >>> print(im.format, im.size, im.mode)
PPM (512, 512) RGB
format屬性定義了圖像的格式,如果圖像不是從文件打開的,那么該屬性值為None;size屬性是一個tuple,表示圖像的寬和高(單位為像素);mode屬性為表示圖像的模式,常用的模式為:L為灰度圖,RGB為真彩色,CMYK為pre-press圖像。
如果文件不能打開,則拋出IOError異常。
當(dāng)有一個Image對象時,可以用Image類的各個方法進(jìn)行處理和操作圖像,例如顯示圖片:
>>> im.show()
ps:標(biāo)準(zhǔn)版本的show()方法不是很有效率,因為它先將圖像保存為一個臨時文件,然后使用xv進(jìn)行顯示。如果沒有安裝xv,該函數(shù)甚至不能工作。但是該方法非常便于debug和test。(windows中應(yīng)該調(diào)用默認(rèn)圖片查看器打開)
讀寫圖片
Pillow庫支持相當(dāng)多的圖片格式。直接使用Image模塊中的open()函數(shù)讀取圖片,而不必先處理圖片的格式,Pillow庫自動根據(jù)文件決定格式。
Image模塊中的save()函數(shù)可以保存圖片,除非你指定文件格式,那么文件名中的擴(kuò)展名用來指定文件格式。
圖片轉(zhuǎn)成jpg格式
from __future__ import print_function import os, sys from PIL import Image for infile in sys.argv[1:]: f, e = os.path.splitext(infile) outfile = f + ".jpg" if infile != outfile: try: Image.open(infile).save(outfile) except IOError: print("cannot convert", infile)
save函數(shù)的第二個參數(shù)可以用來指定圖片格式,如果文件名中沒有給出一個標(biāo)準(zhǔn)的圖像格式,那么第二個參數(shù)是必須的。
創(chuàng)建縮略圖
from __future__ import print_function import os, sys from PIL import Image size = (128, 128) for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + ".thumbnail" if infile != outfile: try: im = Image.open(infile) im.thumbnail(size) im.save(outfile, "JPEG") except IOError: print("cannot create thumbnail for", infile)
必須指出的是除非必須,Pillow不會解碼或raster數(shù)據(jù)。當(dāng)你打開一個文件,Pillow通過文件頭確定文件格式,大小,mode等數(shù)據(jù),余下數(shù)據(jù)直到需要時才處理。
這意味著打開文件非??欤c文件大小和壓縮格式無關(guān)。下面的程序用來快速確定圖片屬性:
確定圖片屬性
from __future__ import print_function import sys from PIL import Image for infile in sys.argv[1:]: try: with Image.open(infile) as im: print(infile, im.format, "%dx%d" % im.size, im.mode) except IOError: pass
裁剪、粘貼、與合并圖片
Image類包含還多操作圖片區(qū)域的方法。如crop()方法可以從圖片中提取一個子矩形
從圖片中復(fù)制子圖像
box = im.copy() #直接復(fù)制圖像 box = (100, 100, 400, 400) region = im.crop(box)
區(qū)域由4-tuple決定,該tuple中信息為(left, upper, right, lower)。 Pillow左邊系統(tǒng)的原點(diǎn)(0,0)為圖片的左上角。坐標(biāo)中的數(shù)字單位為像素點(diǎn),所以上例中截取的圖片大小為300*300像素^2。
處理子圖,粘貼回原圖
region = region.transpose(Image.ROTATE_180) im.paste(region, box)
將子圖paste回原圖時,子圖的region必須和給定box的region吻合。該region不能超過原圖。而原圖和region的mode不需要匹配,Pillow會自動處理。
另一個例子
Rolling an image def roll(image, delta): "Roll an image sideways" image = image.copy() #復(fù)制圖像 xsize, ysize = image.size delta = delta % xsize if delta == 0: return image part1 = image.crop((0, 0, delta, ysize)) part2 = image.crop((delta, 0, xsize, ysize)) image.paste(part2, (0, 0, xsize-delta, ysize)) image.paste(part1, (xsize-delta, 0, xsize, ysize)) return image
分離和合并通道
r, g, b = im.split() im = Image.merge("RGB", (b, g, r))
對于單通道圖片,split()返回圖像本身。為了處理單通道圖片,必須先將圖片轉(zhuǎn)成RGB。
幾何變換
Image類有resize()、rotate()和transpose()、transform()方法進(jìn)行幾何變換。
簡單幾何變換
out = im.resize((128, 128)) out = im.rotate(45) # 順時針角度表示
置換圖像
out = im.transpose(Image.FLIP_LEFT_RIGHT) out = im.transpose(Image.FLIP_TOP_BOTTOM) out = im.transpose(Image.ROTATE_90) out = im.transpose(Image.ROTATE_180) out = im.transpose(Image.ROTATE_270)
transpose()和象的rotate()沒有性能差別。
更通用的圖像變換方法可以使用transform()
模式轉(zhuǎn)換
convert()方法
模式轉(zhuǎn)換
im = Image.open('lena.ppm').convert('L')
圖像增強(qiáng)
Filter
ImageFilter模塊包含很多預(yù)定義的增強(qiáng)filters,通過filter()方法使用
應(yīng)用filters
from PIL import ImageFilter out = im.filter(ImageFilter.DETAIL)
像素點(diǎn)處理
point()方法通過一個函數(shù)或者查詢表對圖像中的像素點(diǎn)進(jìn)行處理(例如對比度操作)。
像素點(diǎn)變換
# multiply each pixel by 1.2 out = im.point(lambda i: i * 1.2)
上述方法可以利用簡單的表達(dá)式進(jìn)行圖像處理,通過組合point()和paste()還能選擇性地處理圖片的某一區(qū)域。
處理單獨(dú)通道
# split the image into individual bands source = im.split() R, G, B = 0, 1, 2 # select regions where red is less than 100 mask = source[R].point(lambda i: i < 100 and 255) # process the green band out = source[G].point(lambda i: i * 0.7) # paste the processed band back, but only where red was < 100 source[G].paste(out, None, mask) # build a new multiband image im = Image.merge(im.mode, source)
注意到創(chuàng)建mask的語句:
mask = source[R].point(lambda i: i < 100 and 255)
該句可以用下句表示
imout = im.point(lambda i: expression and 255)
如果expression為假則返回expression的值為0(因為and語句已經(jīng)可以得出結(jié)果了),否則返回255。(mask參數(shù)用法:當(dāng)為0時,保留當(dāng)前值,255為使用paste進(jìn)來的值,中間則用于transparency效果)
高級圖片增強(qiáng)
對其他高級圖片增強(qiáng),應(yīng)該使用ImageEnhance模塊 。一旦有一個Image對象,應(yīng)用ImageEnhance對象就能快速地進(jìn)行設(shè)置。 可以使用以下方法調(diào)整對比度、亮度、色平衡和銳利度。
圖像增強(qiáng)
from PIL import ImageEnhance enh = ImageEnhance.Contrast(im) enh.enhance(1.3).show("30% more contrast")
動態(tài)圖
Pillow支持一些動態(tài)圖片的格式如FLI/FLC,GIF和其他一些處于實驗階段的格式。TIFF文件同樣可以包含數(shù)幀圖像。
當(dāng)讀取動態(tài)圖時,PIL自動讀取動態(tài)圖的第一幀,可以使用seek和tell方法讀取不同幀。
from PIL import Image im = Image.open("animation.gif") im.seek(1) # skip to the second frame try: while 1: im.seek(im.tell()+1) # do something to im except EOFError: pass # end of sequence
當(dāng)讀取到最后一幀時,Pillow拋出EOFError異常。
當(dāng)前版本只允許seek到下一幀。為了倒回之前,必須重新打開文件。
或者可以使用下述迭代器類
動態(tài)圖迭代器類
class ImageSequence: def __init__(self, im): self.im = im def __getitem__(self, ix): try: if ix: self.im.seek(ix) return self.im except EOFError: raise IndexError # end of sequence for frame in ImageSequence(im): # ...do something to frame... Postscript Printing
Pillow允許通過Postscript Printer在圖片上添加images、text、graphics。
Drawing Postscript from PIL import Image from PIL import PSDraw im = Image.open("lena.ppm") title = "lena" box = (1*72, 2*72, 7*72, 10*72) # in points ps = PSDraw.PSDraw() # default is sys.stdout ps.begin_document(title) # draw the image (75 dpi) ps.image(box, im, 75) ps.rectangle(box) # draw centered title ps.setfont("HelveticaNarrow-Bold", 36) w, h, b = ps.textsize(title) ps.text((4*72-w/2, 1*72-h), title) ps.end_document()
更多讀取圖片方法
之前說到Image模塊的open()函數(shù)已經(jīng)足夠日常使用。該函數(shù)的參數(shù)也可以是一個文件對象。
從string中讀取
import StringIO im = Image.open(StringIO.StringIO(buffer))
從tar文件中讀取
from PIL import TarIO fp = TarIO.TarIO("Imaging.tar", "Imaging/test/lena.ppm") im = Image.open(fp)
草稿模式
draft()方法允許在不讀取文件內(nèi)容的情況下盡可能(可能不會完全等于給定的參數(shù))地將圖片轉(zhuǎn)成給定模式和大小,這在生成縮略圖的時候非常有效(速度要求比質(zhì)量高的場合)。
draft模式
from __future__ import print_function im = Image.open(file) print("original =", im.mode, im.size) im.draft("L", (100, 100)) print("draft =", im.mode, im.size)
相關(guān)文章
python?selenium實現(xiàn)登錄豆瓣示例詳解
大家好,本篇文章主要講的是python?selenium登錄豆瓣示例詳解,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-01-01python實現(xiàn)計算資源圖標(biāo)crc值的方法
這篇文章主要介紹了python實現(xiàn)計算資源圖標(biāo)crc值的方法,通過解析資源文件找到icon的數(shù)據(jù),從而實現(xiàn)該功能,需要的朋友可以參考下2014-10-10python淘寶準(zhǔn)點(diǎn)秒殺搶單的實現(xiàn)示例
為了想要搶到想要的商品,想了個用Python實現(xiàn)python淘寶準(zhǔn)點(diǎn)秒殺搶單方案,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05flask路由分模塊管理及自定義restful響應(yīng)格式詳解
這篇文章主要為大家介紹了flask路由分模塊管理及自定義restful響應(yīng)格式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08python中根據(jù)字符串調(diào)用函數(shù)的實現(xiàn)方法
下面小編就為大家?guī)硪黄猵ython中根據(jù)字符串調(diào)用函數(shù)的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考,一起跟隨小編過來看看吧2016-06-06