1. win7環境下python怎麼安裝第三方庫
你可以在cmd模式下輸入pip -h,可以獲得詳細的pip指令信息,如下圖: 我只用過pip的install命令,用來下載安裝第三方庫。比如想安裝的第三方庫的名字是Pillow,那麼在命令行輸入: pip install Pillow 然後pip會選擇適合你的python版本的Pillow版本,如果找到適用的版本,就會自動下載安裝。
2. Python圖像處理庫Pillow
Pillow庫安裝成功後,導包時要用PIL來導入 ,而不能用pillow或Pillow。
運行結果:
3. python的pillow庫怎麼使用
Pillow是Python里的圖像處理庫(PIL:Python Image Library),提供了了廣泛的文件格式支持,強大的圖像處理能力,主要包括圖像儲存、圖像顯示、格式轉換以及基本的圖像處理操作等。
1)使用 Image 類
PIL最重要的類是 Image class, 你可以通過多種方法創建這個類的實例;你可以從文件載入圖像,或者處理其他圖像, 或者從 scratch 創建。
要從文件載入圖像,可以使用open( )函數,在Image模塊中:
[python]view plain
>>>fromPILimportImage
>>>im=Image.open("E:/photoshop/1.jpg")
載入成功後,將返回一個Image對象,可以通過使用示例屬性查看文件內容:
[python]view plain
>>>print(im.format,im.size,im.mode)
('JPEG',(600,351),'RGB')
>>>
format這個屬性標識了圖像來源。如果圖像不是從文件讀取它的值就是None。size屬性是一個二元tuple,包含width和height(寬度和高度,單位都是px)。mode屬性定義了圖像bands的數量和名稱,以及像素類型和深度。常見的modes 有 「L」 (luminance) 表示灰度圖像, 「RGB」 表示真彩色圖像, and 「CMYK」 表示出版圖像。
如果文件打開錯誤,返回IOError錯誤。
只要你有了 Image 類的實例,你就可以通過類的方法處理圖像。比如,下列方法可以顯示圖像:
[python]view plain
im.show()
2)讀寫圖像
PIL 模塊支持大量圖片格式。使用在 Image 模塊的 open() 函數從磁碟讀取文件。你不需要知道文件格式就能打開它,這個庫能夠根據文件內容自動確定文件格式。要保存文件,使用 Image 類的 save() 方法。保存文件的時候文件名變得重要了。除非你指定格式,否則這個庫將會以文件名的擴展名作為格式保存。
載入文件,並轉化為png格式:
[python]view plain
"PythonImageLibraryTest"
fromPILimportImage
importos
importsys
forinfileinsys.argv[1:]:
f,e=os.path.splitext(infile)
outfile=f+".png"
ifinfile!=outfile:
try:
Image.open(infile).save(outfile)
exceptIOError:
print("Cannotconvert",infile)
save() 方法的第二個參數可以指定文件格式。
3)創建縮略圖
縮略圖是網路開發或圖像軟體預覽常用的一種基本技術,使用Python的Pillow圖像庫可以很方便的建立縮略圖,如下:
[python]view plain
#createthumbnail
size=(128,128)
forinfileinglob.glob("E:/photoshop/*.jpg"):
f,ext=os.path.splitext(infile)
img=Image.open(infile)
img.thumbnail(size,Image.ANTIALIAS)
img.save(f+".thumbnail","JPEG")
上段代碼對photoshop下的jpg圖像文件全部創建縮略圖,並保存,glob模塊是一種智能化的文件名匹配技術,在批圖像處理中經常會用到。
注意:Pillow庫不會直接解碼或者載入圖像柵格數據。當你打開一個文件,只會讀取文件頭信息用來確定格式,顏色模式,大小等等,文件的剩餘部分不會主動處理。這意味著打開一個圖像文件的操作十分快速,跟圖片大小和壓縮方式無關。
4)圖像的剪切、粘貼與合並操作
Image 類包含的方法允許你操作圖像部分選區,PIL.Image.Image.crop 方法獲取圖像的一個子矩形選區,如:
[python]view plain
#crop,pasteandmerge
im=Image.open("E:/photoshop/lena.jpg")
box=(100,100,300,300)
region=im.crop(box)
矩形選區有一個4元元組定義,分別表示左、上、右、下的坐標。這個庫以左上角為坐標原點,單位是px,所以上訴代碼復制了一個 200x200 pixels 的矩形選區。這個選區現在可以被處理並且粘貼到原圖。
[python]view plain
region=region.transpose(Image.ROTATE_180)
im.paste(region,box)
當你粘貼矩形選區的時候必須保證尺寸一致。此外,矩形選區不能在圖像外。然而你不必保證矩形選區和原圖的顏色模式一致,因為矩形選區會被自動轉換顏色。
5)分離和合並顏色通道
對於多通道圖像,有時候在處理時希望能夠分別對每個通道處理,處理完成後重新合成多通道,在Pillow中,很簡單,如下:
[python]view plain
r,g,b=im.split()
im=Image.merge("RGB",(r,g,b))
對於split( )函數,如果是單通道的,則返回其本身,否則,返回各個通道。
6)幾何變換
對圖像進行幾何變換是一種基本處理,在Pillow中包括resize( )和rotate( ),如用法如下:
[python]view plain
out=im.resize((128,128))
out=im.rotate(45)#degreeconter-clockwise
其中,resize( )函數的參數是一個新圖像大小的元祖,而rotate( )則需要輸入順時針的旋轉角度。在Pillow中,對於一些常見的旋轉作了專門的定義:
[python]view plain
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)
7)顏色空間變換
在處理圖像時,根據需要進行顏色空間的轉換,如將彩色轉換為灰度:
[python]view plain
cmyk=im.convert("CMYK")
gray=im.convert("L")
8)圖像濾波
圖像濾波在ImageFilter 模塊中,在該模塊中,預先定義了很多增強濾波器,可以通過filter( )函數使用,預定義濾波器包括:
BLUR、CONTOUR、DETAIL、EDGE_ENHANCE、EDGE_ENHANCE_MORE、EMBOSS、FIND_EDGES、SMOOTH、SMOOTH_MORE、SHARPEN。其中BLUR就是均值濾波,CONTOUR找輪廓,FIND_EDGES邊緣檢測,使用該模塊時,需先導入,使用方法如下:
[python]view plain
fromPILimportImageFilter
imgF=Image.open("E:/photoshop/lena.jpg")
outF=imgF.filter(ImageFilter.DETAIL)
conF=imgF.filter(ImageFilter.CONTOUR)
edgeF=imgF.filter(ImageFilter.FIND_EDGES)
imgF.show()
outF.show()
conF.show()
edgeF.show()
除此以外,ImageFilter模塊還包括一些擴展性強的濾波器:
classPIL.ImageFilter.GaussianBlur(radius=2)
Gaussian blur filter.
參數:
radius– Blur radius.classPIL.ImageFilter.UnsharpMask(radius=2,percent=150,threshold=3)
Unsharp mask filter.
See Wikipedia』s entry ondigital unsharp maskingfor an explanation of the parameters.
classPIL.ImageFilter.Kernel(size,kernel,scale=None,offset=0)
Create a convolution kernel. The current version only supports 3x3 and 5x5 integer and floating point kernels.
In the current version, kernels can only be applied to 「L」 and 「RGB」 images.
參數:
size– Kernel size, given as (width, height). In the current version, this must be (3,3) or (5,5).
kernel– A sequence containing kernel weights.
scale– Scale factor. If given, the result for each pixel is divided by this value. the default is the sum of the kernel weights.
offset– Offset. If given, this value is added to the result, after it has been divided by the scale factor.
classPIL.ImageFilter.RankFilter(size,rank)
Create a rank filter. The rank filter sorts all pixels in a window of the given size, and returns therank『th value.
參數:
size– The kernel size, in pixels.
rank– What pixel value to pick. Use 0 for a min filter,size*size/2for a median filter,size*size-1for a max filter, etc.
classPIL.ImageFilter.MedianFilter(size=3)
Create a median filter. Picks the median pixel value in a window with the given size.
參數:
size– The kernel size, in pixels.classPIL.ImageFilter.MinFilter(size=3)
Create a min filter. Picks the lowest pixel value in a window with the given size.
參數:
size– The kernel size, in pixels.classPIL.ImageFilter.MaxFilter(size=3)
Create a max filter. Picks the largest pixel value in a window with the given size.
參數:
size– The kernel size, in pixels.classPIL.ImageFilter.ModeFilter(size=3)
Create a mode filter. Picks the most frequent pixel value in a box with the given size. Pixel values that occur only once or twice are ignored; if no pixel value occurs more than twice, the original pixel value is preserved.
參數:
size– The kernel size, in pixels.更多詳細內容可以參考:PIL/ImageFilter
9)圖像增強
圖像增強也是圖像預處理中的一個基本技術,Pillow中的圖像增強函數主要在ImageEnhance模塊下,通過該模塊可以調節圖像的顏色、對比度和飽和度和銳化等:
[python]view plain
fromPILimportImageEnhance
imgE=Image.open("E:/photoshop/lena.jpg")
imgEH=ImageEnhance.Contrast(imgE)
imgEH.enhance(1.3).show("30%morecontrast")
圖像增強:
classPIL.ImageEnhance.Color(image)
Adjust image color balance.
This class can be used to adjust the colour balance of an image, in a manner similar to the controls on a colour TV set. An enhancement factor of 0.0 gives a black and white image. A factor of 1.0 gives the original image.
classPIL.ImageEnhance.Contrast(image)
Adjust image contrast.
This class can be used to control the contrast of an image, similar to the contrast control on a TV set. An enhancement factor of 0.0 gives a solid grey image. A factor of 1.0 gives the original image.
classPIL.ImageEnhance.Brightness(image)
Adjust image brightness.
This class can be used to control the brighntess of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
classPIL.ImageEnhance.Sharpness(image)
Adjust image sharpness.
This class can be used to adjust the sharpness of an image. An enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image.
圖像增強的詳細內容可以參考:PIL/ImageEnhance
除了以上介紹的內容外,Pillow還有很多強大的功能:
PIL.Image.alpha_composite(im1,im2)
PIL.Image.blend(im1,im2,alpha)
PIL.Image.composite(image1,image2,mask)
PIL.Image.eval(image,*args)
PIL.Image.fromarray(obj,mode=None)
PIL.Image.frombuffer(mode,size,data,decoder_name='raw',*args)
4. 怎樣安裝python的圖像處理庫pillow
找到easy_install.exe工具。在windows下安裝Python後,在其安裝路徑下的scripts文件中默認安裝好了easy_install工具。完整路徑如下例:D:\Python27\Scripts\easy_install.exe;其中為我python的安裝路徑,大家可以根據自己的安裝路徑更改。
使用easy_install.exe工具一鍵安裝pip.打開cmd,輸入安裝命令。操作命令如下圖所示:
pip安裝成功後,在cmd下執行pip,將會有如下提示。
再通過pip進行一鍵安裝Pillow。pip類似RedHat裡面的yum,安裝Python包非常方便。操作命令如下圖所示:
5
到這一步就安裝好了。馬上用起來吧,下圖是用這個庫將圖片轉換的字元畫。轉換後有點大,分割成兩張了。
5. 安裝python庫Pillow(PIL)出現問題及解決方法
安裝 PIL ,問題多多,現將出現問題,原因,以及解決方法總結如下:
PIL 的官方版本,但是最後一次維護是2009年,現以宣布停止維護,可以運行在python2.7上。
Pillow PIL 的fork版本,還在繼續維護更新,建議安裝 Pillow 。
在安裝Pillow之前,請卸載PIL
安裝Pillow 依賴,下面安裝是真對ubuntu14.04版本
下面介紹各包提供功能,以及需要的包版本限制(重要)
在我的 ubuntu14.04 中 openjpeg 版本過低,所以找到 openjpeg 的官方網站編譯安裝最新版的 openjpeg
完成依賴安裝後,使用命令 sudo pip install Pillow 安裝Pillow
在我的ubuntu 14.04安裝成功後,在導入仍然提示: [PIL - libopenjp2.so: cannot open shared object file: No such file or directory] 這樣的錯誤,在stackoverflow找到了解決方法:
6. python如何安裝pil庫
PIL:Python Imaging Library,已經是Python平台事實上的圖像處理標准庫了。
由於PIL僅支持到Python 2.7,加上年久失修,於是一群志願者在PIL的基礎上創建了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了許多新特性,因此,我們可以直接安裝使用Pillow。
安裝Python時已經把pip3也備好了,可以直接使用pip3安裝PIL
命令行:pip3 install pillow
注意:
1.PIL安裝包名字的pillow
2.使用pip3命令時,是要在pip3.exe所在路徑下才能執行。一般pip3.exe是在python安裝目錄下的Script文件夾中。
更多Python相關技術文章,請訪問Python教程欄目進行學習!以上就是小編分享的關於python如何安裝pil庫的詳細內容希望對大家有所幫助,更多有關python教程請關注環球青藤其它相關文章!
7. ❤️【Python從入門到精通】(二十七)更進一步的了解Pillow吧!
本文是接上一篇 ❤️【Python從入門到精通】(二十六)用Python的PIL庫(Pillow)處理圖像真的得心應手❤️ 進一步介紹Pillow庫的使用, 本文將重點介紹一些高級特性:比如如何利用Pillow畫圖形(圓形,正方形),介紹通過Pillow庫給圖片添加水印;同時對上一篇文章未介紹的常用知識點進行補充說明。希望對讀者朋友們有所幫助。
上一篇文章已經介紹了Image模塊,但是介紹的還不夠全面,例如如何從網頁中讀取圖片沒有介紹到,如何裁剪圖片都沒有介紹到。
讀取網頁中的圖片的基本實現方式是:首先利用requests庫讀取當前圖片鏈接的內容,接著將內容轉成二進制數據,在通過open方法將該二進制數據,最後通過save方法進行保存。
讀取結果是:
通過crop方法可以從圖片中裁剪出一個指定大小的區域。裁取的區域范圍是 (left, upper, right, lower) 比如從某個寬高都是400的圖片中裁剪一個是寬高都是100的正方形區域,只需要指定裁剪區域的坐標是: (0, 0, 100, 100)
有裁剪還有一個方法就是重新設置圖片大小的方法 resize,比如將前面400 400的圖片 修改成 300 200,只需要調用resize方法
通過 convert方法進行圖片模式的轉換
前面介紹的ImageDraw庫,只是介紹了利用它來向圖片寫入文本,其實ImageDraw模塊還有一個更有用的途徑,就是可以通過它來畫各種圖形。
首先創建一個600*600的畫布。然後再畫布中畫出一個正方形,畫直線的方法是 line方法。
ImageDraw.line(xy, fill=None, width=0, joint=None)
在xy的坐標之間畫一條直線
xy--> 在兩個坐標點之間畫一條直線,坐標點的傳入方式是[(x, y), (x, y), ...]或者[x, y, x, y, ...]
fill--> 直線的顏色
width--> 直線的寬度
畫一個邊框寬度為2px,顏色為藍色的,面積為400*400的正方形。
ImageDraw.arc(xy, start, end, fill=None, width=0)
在給定的區域范圍內,從開始角到結束角之間繪制一條圓弧
xy--> 定義邊界框的兩個點,傳入的格式是[ (x0, y0), (x1, y1)] 或者 [x0, y0, x1, y1] ,其中 x1>=x0,y1>=y0
start --> 起始角度,以度為單位,從3點鍾開始順時針增加
end--> 結束角度,以度為單位
fill--> 弧線的顏色
width-->弧線的寬度
這里就是畫了一個半圓,如果結束角度是360度的話則就會畫一個完整的圓。
畫圓通過ImageDraw.ellipse(xy, fill=None, outline=None, width=1) 方法,該方法可以畫出一個給定范圍的圓
xy--> 定義邊界框的兩個點,傳入的格式是[ (x0, y0), (x1, y1)] 或者 [x0, y0, x1, y1] ,其中 x1>=x0,y1>=y0
outline--> 輪廓的顏色
fill ---> 填充顏色
width--> 輪廓的寬度
ImageDraw.chord(xy, start, end, fill=None, outline=None, width=1) 方法用來畫半圓,跟arc()方法不同的是它會用直線將起始點和結束點連接起來
xy--> 定義邊界框的兩個點,傳入的格式是[ (x0, y0), (x1, y1)] 或者 [x0, y0, x1, y1] ,其中 x1>=x0,y1>=y0
outline--> 輪廓的顏色
fill ---> 填充顏色
width--> 輪廓的寬度
ImageDraw.pieslice(xy, start, end, fill=None, outline=None, width=1)
類似於arc()方法,不過他會在端點和圓點之間畫直線
xy--> 定義邊界框的兩個點,傳入的格式是[ (x0, y0), (x1, y1)] 或者 [x0, y0, x1, y1] ,其中 x1>=x0,y1>=y0
start --> 起始角度,以度為單位,從3點鍾開始順時針增加
end--> 結束角度,以度為單位
fill--> 弧線的顏色
width-->弧線的寬度
ImageDraw.rectangle(xy, fill=None, outline=None, width=1)
xy--> 在兩個坐標點之間畫一條直線,坐標點的傳入方式是[(x, y), (x, y), ...]或者[x, y, x, y, ...]
outline--> 輪廓的顏色
fill--> 填充的顏色
width--> 輪廓線的寬度
ImageDraw.rounded_rectangle(xy, radius=0, fill=None, outline=None, width=1) 該方法可以畫一個圓角矩形
xy--> 在兩個坐標點之間畫一條直線,坐標點的傳入方式是[(x, y), (x, y), ...]或者[x, y, x, y, ...]
radius--> 角的半徑
outline--> 輪廓的顏色
fill--> 填充的顏色
width--> 輪廓線的寬度
這里有個問題,就是畫好的圖形如何從Image中扣出來呢?
ImageEnhance模塊主要是用於設置圖片的顏色對比度亮度銳度等啥的,增強圖像。
原始圖像
ImageFilter模塊主要用於對圖像進行過濾,增強邊緣,模糊處理,該模塊的使用方式是 im.filter(ImageFilter) 。
其中ImageFilter按照需求傳入指定的過濾值。
下面一個個試下效果
4.邊緣增強
ImageGrab模塊主要用於對屏幕進行截圖,通過grab方法進行截取,如果不傳入任何參數則表示全屏幕截圖,否則是截取指定區域的圖像。其中box格式是:(x1,x2,y1,y2)
利用Pillow庫可以輕易的對圖像增加水印
首先,用PIL的Image函數讀取圖片
接著,新建一張圖(尺寸和原圖一樣)
然後,在新建的圖象上用PIL的ImageDraw把字給畫上去,字的顏色從原圖處獲取。
原圖
添加文字後的效果圖
本文詳細介紹了Pillow庫的使用,希望對讀者朋友們有所幫助。
Pillow官方文檔
需要獲取源碼的小夥伴可以關注下方的公眾號,回復【python】
8. 怎麼樣在Python編程中使用Pillow來處理圖像
安裝
剛接觸Pillow的朋友先來看一下Pillow的安裝方法,在這里我們以Mac OS環境為例: (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)、安裝過程中命令行出現錯誤提示:」error: command 『clang' failed with exit status
1」。上網查閱,發現需要通過 Xcode 更新 Command Line Tool。於是打開
Xcode->Preferences->Downloads-Components選項卡。咦?竟然沒了 Command Line
Tools。再查,發現 Xcode 5 以上現在需要用命令行安裝:
$ xcode-select —install
系統會彈出安裝命令行工具的提示,點擊安裝即可。
此時再 pip install pillow,就安裝成功了。
pip freeze 命令查看已經安裝的 Python 包,Pillow 已經乖乖躺那兒了。
好了,下面開始進入教程~
Image類
Pillow中最重要的類就是Image,該類存在於同名的模塊中。可以通過以下幾種方式實例化:從文件中讀取圖片,處理其他圖片得到,或者直接創建一個圖片。
使用Image模塊中的open函數打開一張圖片:
>>> from PIL import Image>>> im = Image.open("lena.ppm")
如果打開成功,返回一個Image對象,可以通過對象屬性檢查文件內容
>>> 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異常。
當有一個Image對象時,可以用Image類的各個方法進行處理和操作圖像,例如顯示圖片:
>>> im.show()
ps:標准版本的show()方法不是很有效率,因為它先將圖像保存為一個臨時文件,然後使用xv進行顯示。如果沒有安裝xv,該函數甚至不能工作。但是該方法非常便於debug和test。(windows中應該調用默認圖片查看器打開)
讀寫圖片
Pillow庫支持相當多的圖片格式。直接使用Image模塊中的open()函數讀取圖片,而不必先處理圖片的格式,Pillow庫自動根據文件決定格式。
Image模塊中的save()函數可以保存圖片,除非你指定文件格式,那麼文件名中的擴展名用來指定文件格式。
圖片轉成jpg格式
from __future__ import print_functionimport os, sysfrom PIL import Imagefor 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函數的第二個參數可以用來指定圖片格式,如果文件名中沒有給出一個標準的圖像格式,那麼第二個參數是必須的。
創建縮略圖
from __future__ import print_functionimport os, sysfrom PIL import Imagesize = (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數據。當你打開一個文件,Pillow通過文件頭確定文件格式,大小,mode等數據,餘下數據直到需要時才處理。
這意味著打開文件非常快,與文件大小和壓縮格式無關。下面的程序用來快速確定圖片屬性:
確定圖片屬性
from __future__ import print_functionimport sysfrom PIL import Imagefor 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類包含還多操作圖片區域的方法。如crop()方法可以從圖片中提取一個子矩形
從圖片中復制子圖像
box = im.() #直接復制圖像box = (100, 100, 400, 400)region = im.crop(box)
區域由4-tuple決定,該tuple中信息為(left, upper, right, lower)。 Pillow左邊系統的原點(0,0)為圖片的左上角。坐標中的數字單位為像素點,所以上例中截取的圖片大小為300*300像素^2。
處理子圖,粘貼回原圖
region = region.transpose(Image.ROTATE_180)im.paste(region, box)
將子圖paste回原圖時,子圖的region必須和給定box的region吻合。該region不能超過原圖。而原圖和region的mode不需要匹配,Pillow會自動處理。
另一個例子
Rolling an imagedef roll(image, delta): "Roll an image sideways" image = image.() #復制圖像 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()返回圖像本身。為了處理單通道圖片,必須先將圖片轉成RGB。
幾何變換
Image類有resize()、rotate()和transpose()、transform()方法進行幾何變換。
簡單幾何變換
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()
模式轉換
convert()方法
模式轉換
im = Image.open('lena.ppm').convert('L')
圖像增強
Filter ImageFilter模塊包含很多預定義的增強filters,通過filter()方法使用
應用filters
from PIL import ImageFilterout = im.filter(ImageFilter.DETAIL)
像素點處理
point()方法通過一個函數或者查詢表對圖像中的像素點進行處理(例如對比度操作)。
像素點變換
# multiply each pixel by 1.2out = im.point(lambda i: i * 1.2)
上述方法可以利用簡單的表達式進行圖像處理,通過組合point()和paste()還能選擇性地處理圖片的某一區域。
處理單獨通道
# split the image into indivial bandssource = im.split()R, G, B = 0, 1, 2# select regions where red is less than 100mask = source[R].point(lambda i: i < 100 and 255)# process the green bandout = source[G].point(lambda i: i * 0.7)# paste the processed band back, but only where red was < 100source[G].paste(out, None, mask)# build a new multiband imageim = Image.merge(im.mode, source)
注意到創建mask的語句:
mask = source[R].point(lambda i: i < 100 and 255)
該句可以用下句表示
imout = im.point(lambda i: expression and 255)
如果expression為假則返回expression的值為0(因為and語句已經可以得出結果了),否則返回255。(mask參數用法:當為0時,保留當前值,255為使用paste進來的值,中間則用於transparency效果)
高級圖片增強
對其他高級圖片增強,應該使用ImageEnhance模塊 。一旦有一個Image對象,應用ImageEnhance對象就能快速地進行設置。 可以使用以下方法調整對比度、亮度、色平衡和銳利度。
圖像增強
from PIL import ImageEnhanceenh = ImageEnhance.Contrast(im)enh.enhance(1.3).show("30% more contrast")
動態圖
Pillow支持一些動態圖片的格式如FLI/FLC,GIF和其他一些處於實驗階段的格式。TIFF文件同樣可以包含數幀圖像。
當讀取動態圖時,PIL自動讀取動態圖的第一幀,可以使用seek和tell方法讀取不同鄭
from PIL import Imageim = Image.open("animation.gif")im.seek(1) # skip to the second frametry: while 1: im.seek(im.tell()+1) # do something to imexcept EOFError: pass # end of sequence
當讀取到最後一幀時,Pillow拋出EOFError異常。
當前版本只允許seek到下一鄭為了倒回之前,必須重新打開文件。
或者可以使用下述迭代器類
動態圖迭代器類
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 sequencefor frame in ImageSequence(im): # ...do something to frame...Postscript Printing
Pillow允許通過Postscript Printer在圖片上添加images、text、graphics。
Drawing Postscriptfrom PIL import Imagefrom PIL import PSDrawim = Image.open("lena.ppm")title = "lena"box = (1*72, 2*72, 7*72, 10*72) # in pointsps = PSDraw.PSDraw() # default is sys.stdoutps.begin_document(title)# draw the image (75 dpi)ps.image(box, im, 75)ps.rectangle(box)# draw centered titleps.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()函數已經足夠日常使用。該函數的參數也可以是一個文件對象。
從string中讀取
import StringIOim = Image.open(StringIO.StringIO(buffer))
從tar文件中讀取
from PIL import TarIOfp = TarIO.TarIO("Imaging.tar", "Imaging/test/lena.ppm")im = Image.open(fp)
草稿模式
draft()方法允許在不讀取文件內容的情況下盡可能(可能不會完全等於給定的參數)地將圖片轉成給定模式和大小,這在生成縮略圖的時候非常有效(速度要求比質量高的場合)。
draft模式
from __future__ import print_functionim = Image.open(file)print("original =", im.mode, im.size)im.draft("L", (100, 100))print("draft =", im.mode, im.size)
9. 如何使用python讀取排版圖片
可以用Pillow庫實現
給個參考:
python利用PIL拼接圖片(九宮格)