附上原文鏈接:http://blog.csdn.net/yockie/article/details/8498301
介紹
把Python的基礎知識學習後,嘗試一下如何安裝、加載、使用非標準庫,選擇了圖像處理模塊PIL。
Python Imaging Library (PIL)是PythonWare公司提供的免費的圖像處理工具包,是python下的圖像處理模塊,支持多種格式,並提供強大的圖形與圖像處理功能。雖然在這個軟件包上要實現類似MATLAB中的複雜的圖像處理算法並不太適合,但是Python的快速開發能力以及面向對象等等諸多特點使得它非常適合用來進行原型開發。對於簡單的圖像處理或者大批量的簡單圖像處理任務,python+PIL是很好的選擇。
PIL 具備(但不限於) 以下的能力:
- 數十種圖檔格式的讀寫能力。 常見的JPEG, PNG, BMP, GIF, TIFF 等格式,都在PIL 的支援之列。 另外,PIL 也支援黑白、灰階、自訂調色盤、RGB true color、帶有透明屬性的RBG true color、CMYK 及其它數種的影像模式。相當齊全。
- 基本的影像資料操作:裁切、平移、旋轉、改變尺寸、調置(transpose)、剪下與貼上等等。
- 強化圖形:亮度、色調、對比、銳利度。
- 色彩處理。
- PIL 提供十數種濾鏡(filter)。 當然,這個數目遠遠不能與Photoshop® 或GIMP® 這樣的專業特效處理軟體相比;但PIL 提供的這些濾鏡可以用在Python 程式裏面,提供批次化處理的能力。
- PIL 可以在影像中繪圖制點、線、面、幾何形狀、填滿、文字等等。
目前PIL的官方最新版本爲1.1.7(官方下載地址:這裏),支持的版本爲python 2.5, 2.6, 2.7,並不支持python3.x,但有高手把它重新編譯生成python3下可安裝的exe了。這一非官方下載地址:這裏。
------------------------------------------------------------------------------------------------------------------------------------------
安裝
由於目前暫未出支持3.x的PIL版本,所以從上述非官方地址中下載了支持3.3的win32版本。需要注意該地址中有兩點說明:
下載完成後 ,基本一直“next”即可安裝。
------------------------------------------------------------------------------------------------------------------------------------------
使用
在PIL中,任何一副圖像都是用一個Image對象表示,而這個類由和它同名的模塊導出,因此,要加載一副圖像,最簡單的形式是這樣的:
由於使用的是非官方的支持3.3版本的PIL,並提示“use `from PIL import Image` instead of `import Image`.”所以本文加載圖像是用如下方式:
PIL提供了豐富的功能模塊:Image,ImageDraw,ImageEnhance,ImageFile等等。最常用到的模塊是Image,ImageDraw,ImageEnhance這三個模塊。
(1)Image模塊
Image模塊是PIL最基本的模塊,其中導出了Image類,一個Image類實例對象就對應了一副圖像。同時,Image模塊還提供了很多有用的函數。打開一副圖像文件 :
這將返回一個Image類實例對象,後面的所有的操作都是在img上完成的。
顯示一幅已經載入的圖片:
調整圖像大小:
原來的圖像大小是256x256,現在,保存的new_img.jpg的大小是128x128。如下:
旋轉圖像:
現在我們把剛纔調整過大小的圖像旋轉45度:
格式轉換:
假設我們要把上面生成的rot_img.jpg轉換成bmp圖像,要做到這一點這太簡單了:只需要在上面的代碼後面添加下面這樣一行即可:
此處save函數只有一個參數,是一個包含文件名和擴展名的字符串。Image類中的save函數在你未指定保存的格式時,自動根據文件名後綴完成格式轉換。另外一種調用方式是:
注:第一個參數爲你要指定保存的文件名,第二個參數爲你要指定保存的圖像格式。
直方圖統計:
Image類實例的histogram()方法能夠對直方圖數據進行統計,並將結果做爲一個列表(list)返回。比如,我們對上面的旋轉後生成的圖像進行直方圖統計:
(2)ImageDraw模塊
ImageDraw模塊提供了基本的圖形能力,這裏的圖形能力指的主要是圖形的繪製能力。PIL庫提供了比較豐富的圖形繪製函數,可以繪製直線、弧線、矩形、多邊形、橢圓、扇形等等。ImageDraw實現了一個Draw類,所有的圖形繪製功能都是在Draw類實例的方法中實現的。
實例化一個Draw類實例很簡單:
繪製直線:
繪製圓:
(3)ImageEnhance模塊
這個模塊提供了一個常用的圖像增強工具箱。可以用來進行色彩增強、亮度增強、對比度增強、圖像尖銳化等等增強操作。所有操作都有相同形式的接口——通過相應類的enhance方法實現:色彩增強通過Color類的enhance方法實現;亮度增強通過Brightness類的enhance方法實現;對比度增強通過Contrast類的enhance方法實現;尖銳化通過Sharpness類的enhance方法實現。所有的操作都需要向類的構造函數傳遞一個Image對象作爲參數,這個參數定義了增強作用的對象。同時所有的操作都返回一個新的Image對象。如果傳給enhance方法的參數是1.0,則不對原圖像做任何改變,直接返回原圖像的一個拷貝。
這個模塊很容易完全掌握,因爲它只有Color、Contrast、Sharpness、Brightness四個類;並且每個類都只有兩個函數__init__和enhance函數,並且這四個類的使用方式和成員函數的使用方式也都是一樣的(只需要一個factor因子)。
亮度增強:
圖像尖銳化:
對比度增強:
色彩增強:
(4)ImageChops模塊
圖片反色,類似於集合操作中的求補集,最大值爲Max,每個像素做減法,取出反色。
公式:out = MAX - image
比較兩個圖片(逐像素的比較),返回一個新的圖片,這個新的圖片是將兩張圖片中的較淡的部分的疊加。也即使說,在某一點上,兩張圖中,哪個的值小則取之。
公式:out = max(img1, img2)
darker:與lighter正好相反。
公式:out = min(img1, img2)
求出兩張圖片的絕對值,逐像素的做減法:
公式:out = abs(img1, img2)
將兩張圖片互相疊加,如果用純黑色與某圖片進行疊加操作,會得到一個純黑色的圖片。如果用純白色與圖片作疊加,圖片不受影響。
公式:out = img1 * img2 / MAX (可以看到,如果時白色,MAX和MAX會約去,返回原始圖片)
screen:先反色,後疊加
公式:out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
add:對兩張圖片進行算術加法,按照以下公式進行計算
公式:out = (img1+img2) / scale + offset
如果尺度和偏移被忽略的化,scale=1.0, offset=0.0,即out = img1 + img2
subtract:對兩張圖片進行算術減法
公式:out = (img1-img2) / scale + offset
(5)ImageColor模塊
The ImageColor module contains colour tables and converters from CSS3-style colour specifiers to RGB tuples. This module is used by Image.new and the ImageDraw module, among others.
詳見:這裏
getrgb(color) ⇒ (red, green, blue)
Convert a colour string to an RGB tuple. If the string cannot be parsed, this function raises a ValueError exception.
(6)ImageFile模塊
The ImageFile module provides support functions for the image open and save functions.In addition, it provides a Parser class which can be used to decode an image piece by piece (e.g. while receiving it over a network connection). This class implements the same consumer interface as the standard sgmllib and xmllib modules.
詳見:這裏
ImageFile.Parser() => Parser instance
Creates a parser object. Parsers cannot be reused.
parser.feed(data)
Feed a string of data to the parser. This method may raise an IOError exception.
parser.close() => image or None
Tells the parser to finish decoding. If the parser managed to decode an image, it returns an Image object. Otherwise, this method raises an IOError exception.
Example(Parse An Image):
(7)ImageFilter模塊
ImageFilter是PIL的濾鏡模塊,當前版本支持10種加強濾鏡,通過這些預定義的濾鏡,可以方便的對圖片進行一些過濾操作,從而去掉圖片中的噪音(部分的消除),這樣可以降低將來處理的複雜度(如模式識別等)。
濾鏡名稱 | 含義 |
ImageFilter.BLUR | 模糊濾鏡 |
ImageFilter.CONTOUR | 輪廓 |
ImageFilter.DETAIL ImageFilter.EDGE_ENHANCE |
邊界加強 |
ImageFilter.EDGE_ENHANCE_MORE | 邊界加強(閥值更大) |
ImageFilter.EMBOSS | 浮雕濾鏡 |
ImageFilter.FIND_EDGES | 邊界濾鏡 |
ImageFilter.SMOOTH | 平滑濾鏡 |
ImageFilter.SMOOTH_MORE | 平滑濾鏡(閥值更大) |
ImageFilter.SHARPEN | 銳化濾鏡 |
要使用PIL的濾鏡功能,需要引入ImageFilter模塊。
(8)ImageFont模塊
The ImageFont module defines a class with the same name. Instances of this class store bitmap fonts, and are used with the text method of the ImageDraw class.
(9)ImageGrab模塊
The ImageGrab module can be used to copy the contents of the screen or the clipboard to a PIL image memory.
The current version works on Windows only.
ImageGrab.grab() => image
ImageGrab.grab(bbox) => image
Take a snapshot of the screen, and return an "RGB" image. The bounding box argument can be used to copy only a part of the screen.
ImageGrab.grabclipboard() => image or list of strings or None
Take a snapshot of the clipboard contents, and return an image object or a list of file names. If the clipboard doesn't contain image data, this function returns None.
You can use isinstance to check if the function returned a valid image object, or something else:
(10)ImageMath模塊
ImageMath 模塊可以用來計算"圖像表達式"。這個模塊僅提供一個eval函數,它帶一個表達式串以及一幅或多幅圖像作參數。這個模塊僅在 PIL Plus 包中可用。
詳見:這裏
(11)ImageOps模塊
The ImageOps module contains a number of 'ready-made' image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images.
詳見:這裏
(12)ImagePalette模塊
要使用ImagePalette 類和相關的函數,要導入ImagePalette 模塊。
詳見:這裏
(13)ImagePath模塊
ImagePath 模塊用來存儲和操作二維向量數據。路徑對象可以被傳到ImageDraw模塊中的方法中。
詳見:這裏
ImagePath.Path(coordinates) => Path instance
創建一個路徑對象。座標表coordinates可以是任何包含2元組 [ (x, y), ... ] 或者數字值 [ x, y, ... ]的序列對象。
(14)ImageQt模塊
The ImageQt module contains support to create PyQt4 QImage objects from PIL images.
詳見:這裏
ImageQt.ImageQt(image)
Creates an ImageQt object from a PIL image object.
(15)ImageSequence模塊
ImageSequence 模塊包含讓你能夠跌代一個圖像序列的包裝類。
詳見:這裏
ImageSequence.Iterator(image) => Iterator instance
創建一個Iterator 對象讓你可以循環遍歷一個序列中的所有幀。
Iterator 類實現 [] 運算符(Operator [] )
你可以用大於等於0的整數作參數調用這個運算符。如果沒有足夠的幀,跌代子會拋出一個IndexError異常。
(16)ImageStat模塊
The ImageStat module calculates global statistics for an image, or for a region of an image.
詳見:這裏
stat.count
stat.sum
stat.mean
stat.stddev
(17)ImageTk模塊
The ImageTk module contains support to create and modify Tkinter BitmapImage and PhotoImage objects from PIL images.
詳見:這裏
(18)ImageWin模塊
The ImageWin module contains support to create and display images on Windows.
詳見:這裏
ImageWin can be used with PythonWin and other user interface toolkits that provide access to Windows device contexts or window handles. For example, Tkinter makes the window handle available via the winfo_id method:
(19)PSDraw模塊
The PSDraw module provides simple print support for Postscript printers. You can print text, graphics and images through this module.
詳見:這裏
------------------------------------------------------------------------------------------------------------------------------------------
參考資料
(1). 《在python3下用PIL做圖像處理》
(2). 《用Python進行圖像處理》
(3).《python圖像處理之初窺門徑》
(4). PIL的《handbook》