PIL詳細文檔
The most important class in the Python Imaging Library is the Image class, defined in the module with the same name. You can create instances of this class in several ways; either by loading images from files, processing other images, or creating images from scratch.
解釋:Python映像庫中最重要的類是Image類,定義在具有相同名稱的模塊中。您可以通過多種方式創建該類的實例;通過從文件加載圖像,處理其他圖像,或從頭創建圖像/。
1、簡單實用Image函數
從文件加載圖像,用Image函數的open方法
>>> from PIL import Image
>>> im = Image.open("hopper.ppm")
如果成功,這個函數將返回一個圖像對象。現在您可以使用實例屬性來檢查文件內容
>>> from __future__ import print_function
>>> print(im.format, im.size, im.mode)
PPM (512, 512) RGB
format屬性識別圖形的源,若圖片不是從文件讀取的將顯示None;
size屬性是一個包含寬度和高度的二元數組(以像素為單位);
mode屬性定義了圖像中波段的數量和名稱,以及像素類型和深度
save 要保存文件,請使用Image類的save()方法
常見的模式是“L”(亮度)用於灰度圖像,“RGB”用於真正的彩色圖像,以及“CMYK”用於預壓圖像
一旦有了Image類的實例,就可以使用該類定義的方法來處理和操作圖像
>>> im.show() #顯示剛剛加載的圖像
show()的標准版本不是很有效,因為它將圖像保存到一個臨時文件中,並調用xv實用程序來顯示圖像。如果你沒有安裝xv,它甚至不會工作。但是,當它確實起作用時,它對於調試和測試非常方便。
例子:創建圖片的縮略圖
im = Image.open('bossimg.jpg')
print im.format,im.size,im.mode
size = (30,40)
im.thumbnail(size) #大小是元組長和寬
im.save('boss.png','PNG') #以png格式保存縮略圖
2、讀寫圖片
1)將文件轉換成JPEG
from __future__ import print_function
import os, sys
from PIL import Image
for 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)
2)創建JPEG縮略圖
from __future__ import print_function
import os, sys
from PIL import Image
size = (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)
3)識別圖像文件
from __future__ import print_function
import sys
from PIL import Image
for 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
3、剪切、粘貼和合並圖像
1)從圖像中復制子矩形
box = (100, 100, 400, 400)
region = im.crop(box)
該區域由一個4元組定義,其中坐標為(左、上、右、下)。Python映像庫使用左上角的(0,0)坐標系統。還要注意,坐標是指像素之間的位置,所以上面例子中的區域正好是300x300像素。
2)處理一個子矩形,並將其粘貼回去
region = region.transpose(Image.ROTATE_180)
im.paste(region, box)
當粘貼區域返回時,區域的大小必須與給定區域完全匹配。此外,該區域不能擴展到圖像之外。然而,原始圖像的模式和區域不需要匹配。如果不這樣做,在粘貼之前,該區域會自動轉換(詳情請參閱下面的顏色轉換部分)。
3)滾動一個圖像
def roll(image, delta):
"Roll an image sideways"
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))
part1.load()
part2.load()
image.paste(part2, (0, 0, xsize-delta, ysize))
image.paste(part1, (xsize-delta, 0, xsize, ysize))
return image
對於更高級的技巧,paste方法還可以使用透明掩碼作為可選參數。在該掩碼中,值255表示粘貼圖像在該位置是不透明的(也就是說,粘貼的圖像應該被使用)。值0表示粘貼的圖像是完全透明的。中間值表示不同級別的透明性。例如,粘貼一個RGBA圖像並使用它作為掩碼會粘貼圖像的不透明部分,而不是它的透明背景。
4)分裂和合並圖像
r, g, b = im.split()
im = Image.merge("RGB", (b, g, r))
注意,對於單個帶圖像,split()返回圖像本身。要使用單獨的顏色組合,您可能需要先將圖像轉換為“RGB”。
4、幾何變換
PIL.Image。Image類包含了調整()和旋轉()圖像的方法。前者采用一個元組來給出新的尺寸,后者是逆時針方向的角度。
The PIL.Image.Image class contains methods to resize() and rotate() an image. The former takes a tuple giving the new size, the latter the angle in degrees counter-clockwise.
1)簡單的幾何變換
out = im.resize((128, 128))
out = im.rotate(45) # degrees counter-clockwise
要在90度的步驟中旋轉圖像,您可以使用rotate()方法或轉置()方法。后者也可以用來在水平或垂直軸上翻轉圖像。
To rotate the image in 90 degree steps, you can either use the rotate() method or the transpose() method. The latter can also be used to flip an image around its horizontal or vertical axis.
2)移位一個圖像
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)
一種更一般的圖像轉換可以通過transform()方法進行。
5、顏色轉換
Python圖像庫允許使用convert()方法在不同的像素表示之間轉換圖像
模式之間的轉換
from PIL import Image
im = Image.open("hopper.ppm").convert("L")
庫支持每個受支持的模式和“L”和“RGB”模式之間的轉換。要在其他模式之間轉換,您可能需要使用中間圖像(通常是“RGB”圖像)。
6、圖象增強
Python圖像庫提供了許多方法和模塊,可用於增強圖像。
1)過濾
ImageFilter模塊包含許多預先定義的增強過濾器,可以與filter()方法一起使用
from PIL import ImageFilter
out = im.filter(ImageFilter.DETAIL)
2)點運算
point()方法可以用來翻譯圖像的像素值(如圖像對比度處理)。在大多數情況下,期望一個參數的函數對象可以傳遞給這個方法。每個像素都是按照該功能進行處理的。
# multiply each pixel by 1.2
out = im.point(lambda i: i * 1.2)
使用上述技術,您可以快速地將任何簡單的表達式應用到圖像中。還可以將point()和paste()方法組合為有選擇地修改圖像
3)處理單個的圖像頻段
# split the image into individual bands
source = im.split()
R, G, B = 0, 1, 2
# select regions where red is less than 100
mask = source[R].point(lambda i: i < 100 and 255)
# process the green band
out = source[G].point(lambda i: i * 0.7)
# paste the processed band back, but only where red was < 100
source[G].paste(out, None, mask)
# build a new multiband image
im = Image.merge(im.mode, source)
創建掩碼的語法:
imout = im.point(lambda i: expression and 255)
4)增強或者優化處理
Python只計算邏輯表達式的部分,以確定結果,並返回作為表達式結果檢查的最后一個值。因此,如果上面的表達式為false(0),Python就不會查看第二個操作數,因此返回0。否則,它將返回255
from PIL import ImageEnhance
enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast")
7、圖像序列
Python映像庫包含對圖像序列(也稱為動畫格式)的一些基本支持。支持的序列格式包括FLI / FLC、GIF和一些實驗格式。TIFF文件也可以包含多個幀。
當打開一個序列文件時,PIL會自動加載序列中的第一幀。您可以使用seek和tell方法在不同的幀之間移動
1)讀序列
from PIL import Image
im = Image.open("animation.gif")
im.seek(1) # skip to the second frame
try:
while 1:
im.seek(im.tell()+1)
im.show()
# do something to im
except EOFError:
pass # end of sequence
如本例中所示,當序列結束時,您將得到一個EOFError異常
下面的類讓您使用for - statement來對序列進行循環
Using the ImageSequence Iterator class
from PIL import ImageSequence
for frame in ImageSequence.Iterator(im):
# ...do something to frame...
8、圖像打印
Python映像庫包括用於在Postscript打印機上打印圖像、文本和圖形的函數
下面是一個簡單的列子簡答說明
from PIL import Image
from PIL import PSDraw
im = Image.open("hopper.ppm")
title = "hopper"
box = (1*72, 2*72, 7*72, 10*72) # in points
ps = PSDraw.PSDraw() # default is sys.stdout
ps.begin_document(title)
# draw the image (75 dpi)
ps.image(box, im, 75)
ps.rectangle(box)
# draw title
ps.setfont("HelveticaNarrow-Bold", 36)
ps.text((3*72, 4*72), title)
ps.end_document()
9、更多的讀取圖像
您可以使用類似文件的對象而不是文件名。對象必須實現read()、seek()和tell()方法,並以二進制模式打開。
1)從打開的文件中讀取
from PIL import Image
with open("hopper.ppm", "rb") as fp:
im = Image.open(fp)
2)從字符串閱讀
import StringIO
im = Image.open(StringIO.StringIO(buffer))
注意,在讀取圖像標題之前,庫會對文件進行重卷(使用查找(0))。此外,當讀取圖像數據時,也會使用seek(通過load方法)。如果圖像文件嵌入到一個較大的文件中,比如tar文件,那么可以使用ContainerIO或TarIO模塊來訪問它
3)從tar壓縮文件中讀取
from PIL import Image, TarIO
fp = TarIO.TarIO("Tests/images/hopper.tar", "hopper.jpg")
im = Image.open(fp)
10、控制譯碼器
一些解碼器允許您在讀取文件時對圖像進行操作。在創建縮略圖(通常速度比質量更重要)和打印到單色激光打印機(只需要一個灰度版本的圖像)時,這通常可以用來加速解碼。
The draft() method manipulates an opened but not yet loaded image so it as closely as possible matches the given mode and size. This is done by reconfiguring the image decoder.
1) 閱讀草稿模式
這只適用於JPEG和MPO文件
from PIL import Image
from __future__ import print_function
im = Image.open(file)
print("original =", im.mode, im.size)
im.draft("L", (100, 100))
print("draft =", im.mode, im.size)
上述執行打印出類似下面:
original = RGB (512, 512)
draft = L (128, 128)
注意,生成的圖像可能與請求的模式和大小不完全匹配。為了確保圖像不大於給定的大小,使用縮略圖方法。