當前位置:
首頁 > 知識 > Python 圖像處理庫 Pillow 入門

Python 圖像處理庫 Pillow 入門

(點擊

上方藍字

,快速關注我們)




來源:Belial_2010


blog.csdn.net/kezunhai/article/details/46446153


如有好文章投稿,請點擊 → 這裡了解詳情




Pillow是Python里的圖像處理庫(PIL:Python Image Library),提供了了廣泛的文件格式支持,強大的圖像處理能力,主要包括圖像儲存、圖像顯示、格式轉換以及基本的圖像處理操作等。



1)使用 Image 類




PIL最重要的類是 Image class, 你可以通過多種方法創建這個類的實例;你可以從文件載入圖像,或者處理其他圖像, 或者從 scratch 創建。




要從文件載入圖像,可以使用open( )函數,在Image模塊中:





>>>

from PIL import

Image


>>>

im

=

Image

.

open

(

"E:/photoshop/1.jpg"

)




載入成功後,將返回一個Image對象,可以通過使用示例屬性查看文件內容:





>>>

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 類的實例,你就可以通過類的方法處理圖像。比如,下列方法可以顯示圖像:




im.show()




2)讀寫圖像




PIL 模塊支持大量圖片格式。使用在 Image 模塊的 open() 函數從磁碟讀取文件。你不需要知道文件格式就能打開它,這個庫能夠根據文件內容自動確定文件格式。要保存文件,使用 Image 類的 save() 方法。保存文件的時候文件名變得重要了。除非你指定格式,否則這個庫將會以文件名的擴展名作為格式保存。




載入文件,並轉化為png格式:





"Python Image Library Test"


from PIL import Image


import os


import sys



for

infile

in

sys

.

argv

[

1

:

]

:


f

,

e

=

os

.

path

.

splitext

(

infile

)


outfile

=

f

+

".png"


if

infile

!=

outfile

:


try

:


Image

.

open

(

infile

).

save

(

outfile

)


except

IOError

:


print

(

"Cannot convert"

,

infile

)




save() 方法的第二個參數可以指定文件格式。




3)創建縮略圖




縮略圖是網路開發或圖像軟體預覽常用的一種基本技術,使用Python的Pillow圖像庫可以很方便的建立縮略圖,如下:





# create thumbnail


size

=

(

128

,

128

)


for

infile

in

glob

.

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 方法獲取圖像的一個子矩形選區,如:





# crop, paste and merge


im

=

Image

.

open

(

"E:/photoshop/lena.jpg"

)


box

=

(

100

,

100

,

300

,

300

)


region

=

im

.

crop

(

box

)




矩形選區有一個4元元組定義,分別表示左、上、右、下的坐標。這個庫以左上角為坐標原點,單位是px,所以上訴代碼複製了一個 200×200 pixels 的矩形選區。這個選區現在可以被處理並且粘貼到原圖。





region

=

region

.

transpose

(

Image

.

ROTATE_180

)


im

.

paste

(

region

,

box

)




當你粘貼矩形選區的時候必須保證尺寸一致。此外,矩形選區不能在圖像外。然而你不必保證矩形選區和原圖的顏色模式一致,因為矩形選區會被自動轉換顏色。




5)分離和合并顏色通道




對於多通道圖像,有時候在處理時希望能夠分別對每個通道處理,處理完成後重新合成多通道,在Pillow中,很簡單,如下:





r

,

g

,

b

=

im

.

split

()


im

=

Image

.

merge

(

"RGB"

,

(

r

,

g

,

b

))




對於split( )函數,如果是單通道的,則返回其本身,否則,返回各個通道。




6)幾何變換




對圖像進行幾何變換是一種基本處理,在Pillow中包括resize( )和rotate( ),如用法如下:





out

=

im

.

resize

((

128

,

128

))


out

=

im

.

rotate

(

45

)

# degree conter-clockwise




其中,resize( )函數的參數是一個新圖像大小的元祖,而rotate( )則需要輸入順時針的旋轉角度。在Pillow中,對於一些常見的旋轉作了專門的定義:





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)顏色空間變換




在處理圖像時,根據需要進行顏色空間的轉換,如將彩色轉換為灰度:





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邊緣檢測,使用該模塊時,需先導入,使用方法如下:





from PIL import ImageFilter



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模塊還包括一些擴展性強的濾波器:




class PIL.ImageFilter.GaussianBlur(radius=2)




Gaussian blur filter.




參數




  • radius – Blur radius.




class PIL.ImageFilter.UnsharpMask(radius=2, percent=150, threshold=3)




Unsharp mask filter.




See Wikipedia』s entry on digital unsharp masking for an explanation of the parameters.




class PIL.ImageFilter.Kernel(size, kernel, scale=None, offset=0)




Create a convolution kernel. The current version only supports 3×3 and 5×5 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.




class PIL.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 / 2 for a median filter, size * size - 1 for a max filter, etc.




class PIL.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.




class PIL.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.




class PIL.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.




class PIL.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模塊下,通過該模塊可以調節圖像的顏色、對比度和飽和度和銳化等:





from PIL import ImageEnhance



imgE

=

Image

.

open

(

"E:/photoshop/lena.jpg"

)


imgEH

=

ImageEnhance

.

Contrast

(

imgE

)


imgEH

.

enhance

(

1.3

).

show

(

"30% more contrast"

)




圖像增強:




class PIL.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.




class PIL.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.




class PIL.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.




class PIL.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)




參考資料:






  1. PLI–Pillow快速入門




看完本文有收穫?請轉

發分享給更多人


關注「Python開發者」,提升Python技能


喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 Python開發者 的精彩文章:

使用 VASPy 快速處理 VASP 文件以及數據可視化
Django 通道簡要介紹

TAG:Python開發者 |

您可能感興趣

Python 數據處理庫 pandas 入門教程
偽 「Photoshop」的圖像處理
Jdk 動態代理異常處理分析,UndeclaredThrowableException
三款照片處理軟體橫評:Lightroom、CaptureOne、AfterShot
Python modbus 浮點型數據處理
Django Channel處理Websocket鏈接
Servlet Cookie 處理
Pytorch 中如何處理 RNN 輸入變長序列 padding
原Movidius CEO Remi El-Ouazzane:深度了解終端視覺處理器VPU
linux-shell命令處理json數據
Android P可以支持虹膜掃描?三星Galaxy S9的處理器比iphoneX慢
Python的Socket知識2:粘包處理
Oculus Santa Cruz或採用高通Snapdragon 845處理器
戴爾用第八代處理器刷新了Alienware和Inspiron產品陣容
Photoshop圖片處理課程
ZUUL 處理 gerrit patch-set 的流程
Google愛上Intel+AMD合體處理器:Chromebook要用它
Photoshop攝影后期處理
iPad找不到Apple Pencil了怎麼處理?
用於自然語言處理的開源 Python庫——PyTorch-NLP