原文地址:http://www.cnblogs.com/way_testlife/archive/2011/04/20/2022997.html
--------------
PIL 中的 Image 模組
本文是節選自 PIL handbook online 並做了一些簡單的翻譯
只能保證自己看懂,不保證翻譯品質。歡迎各位給出意見。
------------------------------------------------------
Image 模組提供了一個同名類(Image),也提供了一些工廠函數,包括從檔案中載入圖片和建立新圖片。例如,以下的指令碼先載入一幅圖片,將它旋轉 45 度角,並顯示出來:
1 >>> from PIL import Image 2 >>> im = Image.open( " j.jpg " ) 3 >>> im.rotate( 45 ).show()
下面這個指令碼則建立了目前的目錄下所有以 .jpg 結尾的圖片的縮圖。
1 from PIL import Image 2 import glob, os 3 4 size = 128 , 128 5 for infile in glob.glob( " *.jpg " ): 6 file, ext = os.path.splitext(infile) 7 im = Image.open(infile) 8 im.thumbnail(size, Image.ANTIALIAS) 9 im.save(file + " .thumbnail " , " JPEG " )
Image 類中的函數。
0. new : 這個函數建立一幅給定模式(mode)和尺寸(size)的圖片。如果省略 color 參數,則建立的圖片被黑色填充滿,如果 color 參數是 None 值,則圖片還沒初始化。
1 Image.new( mode, size ) => image 2 Image.new( mode, size, color ) => image
1. open : 開啟並識別所提供的影像檔。不過,使用這函數的時候,真正的映像資料在你進行資料處理之前並沒有被讀取出來。可使用 load 函數進行強制載入。 mode 參數可以省略,但它只能是 "r" 值。
1 Image.open( infile ) => image 2 Image.open( infile, mode ) => image
2. blend : 使用兩幅給出的圖片和一個常量 alpha 建立新的圖片。兩幅圖片必須是同樣的 size 和 mode 。
1 Image.blend( image1, image2, alpha ) => image 2 # 結果 與 運算過程 3 # out = image1 * ( 1.0 - alpha ) + image2 * alpha
3. composite : 使用兩幅給出的圖片和一個與 alpha 參數相似用法的 mask 參數,其值可為:"1", "L", "RGBA" 。兩幅圖片的 size 必須相同。
1 Image.composite( image1, image2, mask ) => image
4. eval : 使用帶一個參數的函數作用於給定圖片的每一個像素。如果給定的圖片有超過一個的 頻段(band),則該函數也會作用於每一個頻段。注意,該函數是每一個像素計算一次,所以不能使用一些隨機組件或其他的產生器。
1 Image.eval( image, function ) => image
5. frombuffer : (PIL 1.1.4 中新添加的)使用標準 "raw" 解碼器在像素資料或是對象緩衝中建立一個映像副本。不是所有的模式都支援這種用法。支援的 mode 有"L", "RGBX", "RGBA", "CMYK"。
Image.frombuffer( mode, size, data ) => image
6. fromstring : 注意,這個函數只對像素資料進行解碼,而不是一整張圖片。如果你有一整張字串格式的圖片,使用 StringIO 對其進行封裝並用 open 函數載入它。
1 # 使用字串類型的像素資料和標準解碼器 "raw" 來建立映像 2 Image.fromstring( mode, size, data ) => image 3 4 # 同上。不過允許你使用其他 PIL 支援的像素解碼器。 5 Image.fromstring( mode, size, data, decoder, parameters ) => image
7. merge : 使用一系列單一頻段(band)的映像來建立新的一幅映像。頻段是以一些映像組成的元組或列表,所有的 band 必須有相同大小的 size 。
1 Image.merge( mode, bands ) => image
Image 類中的方法:
0. convert : 返回一個轉換後的映像的副本。
1 # If mode is omitted, a mode is chosed so that all information in the image and the palette can be representedwithout a palette . 2 # when from a colour image to black and white, the library uses the ITU-R 601-2 luma transfrom: 3 # L = R * 299/1000 + G * 587/1000 + B * 114/1000 4 im.convert( mode ) => image 5 6 # Converts an "RGB" image to "L" or "RGB" using a conversion matrix. The matrix is 4- or 16-tuple. 7 im.convert( mode, matrix ) => image
下面是一個例子:轉換 RGB 為 XYZ 。
1 rgb2xyz = ( 2 0.412453 , 0.357580 , 0.180423 , 0, 3 0.212671 , 0.715160 , 0.072169 , 0, 4 0.019334 , 0.119193 , 0.950227 , 0 ) 5 out = im.convert( " RGB " , rgb2xyz)
1. copy : 複製映像。如果你希望粘貼一些東西進映像裡面的話可以使用這個方法,但仍然會保留原映像。
1 im.copy() => image
2. crop :