python的PIL工具包入門

附上原文鏈接: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了。這一非官方下載地址:這裏

       這裏是PIL的使用手冊,這裏有中文版。

------------------------------------------------------------------------------------------------------------------------------------------

安裝

        由於目前暫未出支持3.x的PIL版本,所以從上述非官方地址中下載了支持3.3的win32版本。需要注意該地址中有兩點說明:

[plain] view plain copy
  1. Note: use `from PIL import Image` instead of `import Image`.  
  2. Note: this fork contains bug fixes and enhancements.  

        下載完成後 ,基本一直“next”即可安裝。

------------------------------------------------------------------------------------------------------------------------------------------

使用

        在PIL中,任何一副圖像都是用一個Image對象表示,而這個類由和它同名的模塊導出,因此,要加載一副圖像,最簡單的形式是這樣的:

[python] view plain copy
  1. import Image   
  2. img = Image.open(“test.jpg”)   

        由於使用的是非官方的支持3.3版本的PIL,並提示“use `from PIL import Image` instead of `import Image`.”所以本文加載圖像是用如下方式:

[python] view plain copy
  1. from PIL import Image  
  2. img = Image.open("test.jpg")  
        PIL提供了豐富的功能模塊:Image,ImageDraw,ImageEnhance,ImageFile等等。最常用到的模塊是Image,ImageDraw,ImageEnhance這三個模塊。

(1)Image模塊

       Image模塊是PIL最基本的模塊,其中導出了Image類,一個Image類實例對象就對應了一副圖像。同時,Image模塊還提供了很多有用的函數。打開一副圖像文件 :

[python] view plain copy
  1. from PIL import Image  
  2. img = Image.open("test.jpg")  

這將返回一個Image類實例對象,後面的所有的操作都是在img上完成的。

        顯示一幅已經載入的圖片:

[python] view plain copy
  1. img.show()  


        

        調整圖像大小

[python] view plain copy
  1. from PIL import Image  
  2. img = Image.open("test.jpg")  
  3. new_img = img.resize((128128), Image.BILINEAR)  
  4. new_img.save("new_img.jpg")  

原來的圖像大小是256x256,現在,保存的new_img.jpg的大小是128x128。如下:



        旋轉圖像: 

        現在我們把剛纔調整過大小的圖像旋轉45度: 

[python] view plain copy
  1. from PIL import Image  
  2. img = Image.open("test.jpg")  
  3. new_img = img.resize((128128), Image.BILINEAR)  
  4. rot_img = new_img.rotate(45)  
  5. rot_img.save("rot_img.jpg")  



        格式轉換
        假設我們要把上面生成的rot_img.jpg轉換成bmp圖像,要做到這一點這太簡單了:只需要在上面的代碼後面添加下面這樣一行即可: 

[python] view plain copy
  1. rot_img.save("con_img.bmp")   

此處save函數只有一個參數,是一個包含文件名和擴展名的字符串。Image類中的save函數在你未指定保存的格式時,自動根據文件名後綴完成格式轉換。另外一種調用方式是:

[python] view plain copy
  1. img.save('con_img','bmp')  

注:第一個參數爲你要指定保存的文件名,第二個參數爲你要指定保存的圖像格式。


        直方圖統計: 

        Image類實例的histogram()方法能夠對直方圖數據進行統計,並將結果做爲一個列表(list)返回。比如,我們對上面的旋轉後生成的圖像進行直方圖統計:

[python] view plain copy
  1. from PIL import Image  
  2. img = Image.open("test.jpg")  
  3. new_img = img.resize((128128), Image.BILINEAR)  
  4. rot_img = new_img.rotate(45)  
  5. print (rot_img.histogram())  


(2)ImageDraw模塊

        ImageDraw模塊提供了基本的圖形能力,這裏的圖形能力指的主要是圖形的繪製能力。PIL庫提供了比較豐富的圖形繪製函數,可以繪製直線、弧線、矩形、多邊形、橢圓、扇形等等。ImageDraw實現了一個Draw類,所有的圖形繪製功能都是在Draw類實例的方法中實現的。

        實例化一個Draw類實例很簡單:

[python] view plain copy
  1. from PIL import Image, ImageDraw  
  2. img = Image.open("test.jpg")  
  3. draw = ImageDraw.Draw(img)  
  4. #.....  
  5. img.save("new.jpg")  


        繪製直線

[python] view plain copy
  1. from PIL import Image, ImageDraw  
  2. img = Image.open("test.jpg")  
  3. draw = ImageDraw.Draw(img)  
  4. width, height = img.size  
  5. draw.line( ( (0,0), (width-1, height-1)), fill=255)  
  6. draw.line( ( (0,height-1), (width-10)), fill=255)  
  7. img.save("cross_line.jpg")  



        繪製圓: 

[python] view plain copy
  1. from PIL import Image, ImageDraw  
  2. img = Image.open("test.jpg")  
  3. draw = ImageDraw.Draw(img)  
  4. width, height = img.size  
  5. draw.arc( (00, width-1, height-1), 0360, fill=255)  
  6. img.save("circle.jpg")  




(3)ImageEnhance模塊

        這個模塊提供了一個常用的圖像增強工具箱。可以用來進行色彩增強、亮度增強、對比度增強、圖像尖銳化等等增強操作。所有操作都有相同形式的接口——通過相應類的enhance方法實現:色彩增強通過Color類的enhance方法實現;亮度增強通過Brightness類的enhance方法實現;對比度增強通過Contrast類的enhance方法實現;尖銳化通過Sharpness類的enhance方法實現。所有的操作都需要向類的構造函數傳遞一個Image對象作爲參數,這個參數定義了增強作用的對象。同時所有的操作都返回一個新的Image對象。如果傳給enhance方法的參數是1.0,則不對原圖像做任何改變,直接返回原圖像的一個拷貝。

        這個模塊很容易完全掌握,因爲它只有Color、Contrast、Sharpness、Brightness四個類;並且每個類都只有兩個函數__init__和enhance函數,並且這四個類的使用方式和成員函數的使用方式也都是一樣的(只需要一個factor因子)。

        亮度增強: 

[python] view plain copy
  1. from PIL import Image, ImageEnhance  
  2. img = Image.open("test.jpg")  
  3. brightness = ImageEnhance.Brightness(img)  
  4. bright_img = brightness.enhance(2.0)  
  5. bright_img.save("bright.jpg")  



        圖像尖銳化: 

[python] view plain copy
  1. from PIL import Image, ImageEnhance  
  2. img = Image.open("test.jpg")  
  3. sharpness = ImageEnhance.Sharpness(img)  
  4. sharp_img = sharpness.enhance(7.0)  
  5. sharp_img.save("sharp.jpg")  



        對比度增強: 

[python] view plain copy
  1. from PIL import Image, ImageEnhance  
  2. img = Image.open("test.jpg")  
  3. contrast = ImageEnhance.Contrast(img)  
  4. contrast_img = contrast.enhance(2.0)  
  5. contrast_img.save("contrast.jpg")  



        色彩增強

[python] view plain copy
  1. from PIL import Image, ImageEnhance  
  2. img = Image.open("test.jpg")  
  3. color = ImageEnhance.Color(img)  
  4. color_img = color.enhance(3.0)  
  5. color_img.save("color.jpg")  


(4)ImageChops模塊

        這個模塊主要包括對圖片的算術運算,叫做通道運算(channel operations)。這個模塊可以用於多種途徑,包括一些特效製作,圖片整合,算數繪圖等等方面。

        圖片反色,類似於集合操作中的求補集,最大值爲Max,每個像素做減法,取出反色。

        公式:out = MAX - image

[python] view plain copy
  1. ImageChops.invert(image)   

        

        比較兩個圖片(逐像素的比較),返回一個新的圖片,這個新的圖片是將兩張圖片中的較淡的部分的疊加。也即使說,在某一點上,兩張圖中,哪個的值小則取之。

        公式:out = max(img1, img2)

[python] view plain copy
  1. ImageChops.lighter(image1, image2)   

        darker:與lighter正好相反。

        公式:out = min(img1, img2)

[python] view plain copy
  1. ImageChops.darker(image1, image2)    

        求出兩張圖片的絕對值,逐像素的做減法

        公式:out = abs(img1, img2)

[python] view plain copy
  1. ImageChops.difference(image1, image2)  

        將兩張圖片互相疊加,如果用純黑色與某圖片進行疊加操作,會得到一個純黑色的圖片。如果用純白色與圖片作疊加,圖片不受影響。

        公式:out = img1 * img2 / MAX  (可以看到,如果時白色,MAX和MAX會約去,返回原始圖片)

[python] view plain copy
  1. ImageChops.multiply(image1, image2)    

        screen:先反色,後疊加

        公式:out = MAX - ((MAX - image1) * (MAX - image2) / MAX)

[python] view plain copy
  1. ImageChops.screen(image1, image2)    

        add:對兩張圖片進行算術加法,按照以下公式進行計算

        公式:out = (img1+img2) / scale + offset

如果尺度和偏移被忽略的化,scale=1.0, offset=0.0,即out = img1 + img2

[python] view plain copy
  1. ImageChops.add(img1, img2, scale, offset)    

        subtract:對兩張圖片進行算術減法

        公式:out = (img1-img2) / scale + offset

[python] view plain copy
  1. ImageChops.subtract(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):

[python] view plain copy
  1. import ImageFile  
  2.   
  3. fp = open("lena.pgm""rb")  
  4.   
  5. p = ImageFile.Parser()  
  6.   
  7. while 1:  
  8.     s = fp.read(1024)  
  9.     if not s:  
  10.         break  
  11.     p.feed(s)  
  12.   
  13. im = p.close()  
  14.   
  15. im.save("copy.jpg")  


(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模塊。

[python] view plain copy
  1. import Image, ImageFilter  
  2.   
  3. def filterDemo():  
  4.     img = Image.open("test.jpg")  
  5.     imgfilted = img.filter(ImageFilter.SHARPEN)  
  6.     #imgfilted.show()  
  7.     imgfilted.save("sharpen.jpg")  
  8.   
  9. if __name__ == "__main__":  
  10.     filterDemo()  


(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.

[python] view plain copy
  1. import ImageFont, ImageDraw  
  2.   
  3. draw = ImageDraw.Draw(image)  
  4.   
  5. # use a bitmap font  
  6. font = ImageFont.load("arial.pil")  
  7.   
  8. draw.text((1010), "hello", font=font)  
  9.   
  10. # use a truetype font  
  11. font = ImageFont.truetype("arial.ttf"15)  
  12.   
  13. draw.text((1025), "world", font=font)  


(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:

[python] view plain copy
  1. im = ImageGrab.grabclipboard()  
  2.   
  3. if isinstance(im, Image.Image):  
  4.     ... got an image ...  
  5. elif im:  
  6.    for filename in im:  
  7.        try:  
  8.            im = Image.open(filename)  
  9.        except IOError:  
  10.            pass # ignore this file  
  11.        else:  
  12.            ... got an image ...  
  13. else:  
  14.     ... clipboard empty ...  


(10)ImageMath模塊

        ImageMath 模塊可以用來計算"圖像表達式"。這個模塊僅提供一個eval函數,它帶一個表達式串以及一幅或多幅圖像作參數。這個模塊僅在 PIL Plus 包中可用。

        詳見:這裏


[python] view plain copy
  1. import Image, ImageMath  
  2.   
  3. im1 = Image.open("image1.jpg")  
  4. im2 = Image.open("image2.jpg")  
  5.   
  6. out = ImageMath.eval("convert(min(a, b), 'L')", a=im1, b=im2)  
  7. out.save("result.png")  

(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 模塊。

        詳見:這裏

[python] view plain copy
  1. #1. 將調色板添加到圖像 (Sequence Syntax)  
  2. palette = []  
  3. for i in range(256):  
  4.     palette.extend((i, i, i)) # grayscale wedge  
  5.   
  6. assert len(palette) == 768  
  7.   
  8. im.putpalette(palette)  
  9.    
  10.   
  11. #2. 將調色板添加到圖像 (Not Yet Supported)  
  12. import ImagePalette  
  13.   
  14. palette = ImagePalette.ImagePalette("RGB")  
  15. palette.putdata(...)  
  16.   
  17. im.putpalette(palette)  
  18.    
  19.   
  20. #3. Getting the Palette Contents Using Resize/Convert  
  21. assert im.mode == "P"  
  22.   
  23. lut = im.resize((2561))  
  24. lut.putdata(range(256))  
  25. lut = lut.convert("RGB").getdata()   
  26.   
  27. # lut now contains a sequence of (r, g, b) tuples  


(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異常。

[python] view plain copy
  1. import Image, ImageSequence  
  2.   
  3. im = Image.open("animation.fli")  
  4.   
  5. index = 1  
  6. for frame in ImageSequence.Iterator(im):  
  7.     frame.save("frame%d.png" % index)  
  8.     index = index + 1  


(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.

        詳見:這裏

[python] view plain copy
  1. ImageTk.BitmapImage(image, options)  
  2. ImageTk.PhotoImage(image)  
  3. photo.paste(image, box)  


(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:

[python] view plain copy
  1. dib = ImageWin.Dib(...)  
  2.   
  3. hwnd = ImageWin.HWND(widget.winfo_id())  
  4. dib.draw(hwnd, xy)  


(19)PSDraw模塊

        The PSDraw module provides simple print support for Postscript printers. You can print text, graphics and images through this module.
        詳見:這裏


[python] view plain copy
  1. ps.line(from, to)  
  2. ps.rectangle(box)  
  3. ps.text(position, text)  
  4. ps.image(box, image, dpi=None)  


------------------------------------------------------------------------------------------------------------------------------------------

參考資料

(1). 《在python3下用PIL做圖像處理
(2). 《用Python進行圖像處理

(3).《python圖像處理之初窺門徑

(4).  PIL的《handbook

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章