版本9和10间的区别
于2006-01-08 18:55:07修订的的版本9
大小: 19305
编辑: czk
备注:
于2006-01-08 19:01:16修订的的版本10
大小: 41186
编辑: czk
备注:
删除的内容标记成这样。 加入的内容标记成这样。
行号 422: 行号 422:
行号 426: 行号 425:
行号 432: 行号 430:
行号 474: 行号 471:


= Image 模块 =

'''Image''' 模块提供了一个同名的类,用来表示一个PIL图像。这个模块同时提供了一些工厂函数,包括从文件读取图像的函数以及创建新图像的函数。

== 例子 ==
下面的脚本读取一幅图像,旋转45度,再把它在Unix上用'''xv'''显示出来,或者在Windows上用'''paint'''显示出来。

'''打开、旋转、显示图像 (使用默认的图像浏览器)''' {{{
 import Image im = Image.open("bride.jpg") im.rotate(45).show() }}}

   下面的脚本创建当前目录中所有JPEG图像的128x128的缩略图。'''创建缩略图'''

   {{{
import glob for infile in glob.glob("*.jpg"): file, ext = os.path.splitext(infile) im = Image.open(infile) im.thumbnail((128, 128), Image.ANTIALIAS) im.save(file + ".thumbnail", "JPEG") }}}

== 函数 ==
=== new ===
 '''Image.new(mode, size)''' => image

'''Image.new(mode, size, color)''' => image

  使用给定的模式和大小创建一个新图像。大小是以2元组的形式给出的。 当创建单通道的图时,color是单个值;当创建多通道图像时,color是一个元组(每个通道一个值)。如果color参数缺省,图像被填充成全黑。如果color是None,则图像不被初始化。

 
=== open ===
 '''Image.open(infile)''' => image

'''Image.open(infile, mode)''' => image

 打开并识别给定的图像文件。这是一个会被延迟(lazy)的操作;实际的图像数据并不马上从文件中读入,而是等到需要处理这些数据的时候才被读入 (可以调用'''load''' 方法强制读入数据)。如果要指定mode参数,则mode必须是"r"。

  你可以使用一个字符串(表示文件名)或者一个文件对象作为infile。在用文件对象时,文件对象必须实现'''read''', '''seek''', 和'''tell''' 方法,而且必须用二进制模式打开。

 
=== blend ===
 '''Image.blend(image1, image2, alpha)''' => image

  对两幅图像用固定的透明度(alpha)插值生成新的图像。输入的两幅图像必须是同样的大小和模式。

 {{{
    out = image1 * (1.0 - alpha) + image2 * alpha }}}

 如果alpha是0.0,则会返回第一幅图像的一个拷贝。如果alpha是1.0,则会返回第二幅图像的一个拷贝。alpha的取值范围没有限制。如果必要,计算结果会被裁减到允许的输出值的范围。

 
=== composite ===
 '''Image.composite(image1, image2, mask)''' => image

 对两幅图像用图像mask作为透明度插值生成新的图像。 mask图像可以是"1", "L", 或者"RGBA"模式。所有的图像必须是同样的大小。

  
=== eval ===
 '''Image.eval(function, image)''' => image

 将函数(应该带一个参数)作用于给定图像的每一个像素。如果图像有多个通道,这个函数会作用于每一个通道。注意,这个函数对于同样的像素值只会被调用一次,因此你不能使用一个随机函数或者其它的像素生成函数来作为函数。

 
=== frombuffer ===
 '''Image.frombuffer(mode, size, data)''' => image

 (PIL 1.1.4 alpha 4中新增。) 对字符串或者缓冲区对象包含的像素数据,使用标准的"raw"解码器来创建图像。。对于某些模式,图像内存可以与原始缓冲区共享同一块内存 (这意味着如果修改原始的缓冲区对象,将会对图像产生影响)。不是所有的模式都能够共享内存;支持的模式包括"L"、"RGBX"、"RGBA"和"CMYK"。对于其他模式,这个函数和'''fromstring'''函数作用相同。

 '''Image.frombuffer(mode, size, data, decoder, parameters)''' => image

 与对应的'''fromstring''' 函数调用相同。

  
=== fromstring ===
 '''Image.fromstring(mode, size, data)''' => image

 从字符串中读取像素数据,使用标准的"raw"解码器创建图像。

 '''Image.fromstring(mode, size, data, decoder, parameters)''' => image

  与前一个函数的区别是,这个函数允许使用你使用任意PIL支持的像素解码器来解码数据。更多有关解码器的信息,参看[decoder.htm 编写自己的文件解码器]。

 注意,这个函数只是解码像素数据,而不是解码整个图像。如果要处理存在字符串中的完整图像,可以使用'''StringIO'''把字符串包装起来然后用[#image-open-function open]方法来装载它。

 
=== merge ===
 '''Image.merge(mode, bands)''' => image

  从一组单通道的图像创建一幅新图像。通道用图像的元组或者列表的形式给出,每一项是模式mode描述的一个通道。所有通道的大小必须相同。

 
== 方法 ==
'''Image''' 类的对象有下列方法。除非特别声明,所有的方法返回一个新的'''Image'''类型对象,包含处理的结果。

=== convert ===
 '''im.convert(mode)''' => image

  返回转换后的图象拷贝。对于"P"模式,这种转换通过调色板进行。如果模式被省略,那么该方法会自动选取一个能够保存所有图像信息和不需要调色板来表示的图像模式。

 当前版本的库支持"L"、"RGB"和"CMYK"模式之间的相互转换。

 当把一幅彩色图像转换成灰度图象(模式"L"),库使用 ITU-R 601-2两度转换公式:

 {{{
    L = R * 299/1000 + G * 587/1000 + B * 114/1000 }}}

 当把一幅灰度图象转换成2值图像(模式"1")时,所有非零值都被转换成255(白)。要使用其它阈值,可以使用'''point'''方法。

  '''im.convert(mode, matrix)''' => image

 将"RGB"模式图像使用一个转换矩阵转换成"RGB"或者"L"模式图像。矩阵是一个四元组或者16元组。

 下面的例子将RGB图像 (根据 ITU-R 709使用 D65 亮度进行过线性校正) 转换成 CIE XYZ颜色空间图像:

 '''Convert RGB to XYZ''' {{{
    rgb2xyz = ( 0.412453, 0.357580, 0.180423, 0, 0.212671, 0.715160, 0.072169, 0, 0.019334, 0.119193, 0.950227, 0 ) out = im.convert("RGB", rgb2xyz) }}}

=== copy ===
 '''im.copy()''' => image

 拷贝图像。使用这个函数把其它东西粘贴到图像中,并保留原来的图像不变。

 
=== crop ===
 '''im.crop(box)''' => image

  返回当前图像的一个矩形区域。box 是一个四元组指定左、上、右、下四个边界的坐标。

 这是一个会被延迟(lazy)的操作。改变原始的图像可能会影响到剪裁生成的图像。为消除这种影响,可以调用裁剪生成的图象的'''load'''方法。

 
=== draft ===
 '''im.draft(mode, size)'''

 配置图像装载器使其能够返回与指定模式尽可能接近的图像。比如说,你可以使用这个函数,将彩色JPEG图像在装载的时候转换成灰度图象,或者从PCD文件中解出128x192的图像。

 注意,这个方法会改变调用的Image对象。如果图像已经被装入,这个方法没有任何作用。

 
=== filter ===
 '''im.filter(filter)''' => image

  返回当前图像经过给定滤波器滤波后的图像。 要查看可用的滤波器,参考'''ImageFilter''' 模块。

 
=== fromstring ===
 '''im.fromstring(data)'''

'''im.fromstring(data, decoder, parameters)'''

 与'''fromstring'''函数基本相同,只是将data装入当前图像。

 
=== getbands ===
 '''im.getbands()''' => tuple of strings

  返回包含每个通道的名字的元组。比如,在RGB图像上调用'''getbands'''返回("R", "G", "B")。

 
=== getbbox ===
 '''im.getbbox()''' => 4-tuple or None

Calculates the bounding box of the non-zero regions in the image. The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. If the image is completely empty, this method returns None.

=== getdata ===
 '''im.getdata()''' => sequence

  返回以像素值序列的形式返回当前图像的内容。图像的像素值从第零行开始被一行一行的连接在一起变成一维线性的序列对象。

 注意,这个方法返回的序列对象是PIL内部数据类型,只支持部分序列操作。可以使用 '''list(im.getdata())'''将其转换为普通的序列对象(比如需要打印)。

 
=== getextrema ===
 '''im.getextrema()''' => 2-tuple

 返回一个二元组包含图像的最小值和最大值。当前版本的PIL中这个方法仅支持单通道图像。

  
=== getpixel ===
 '''im.getpixel(xy)''' => value or tuple

 返回指定位置的像素值。如果图像是多层(multi-layer)图像,该方法返回一个元组。

 注意,这个方法相当慢;如果你需要处理大量的图像数据,使用'''getdata'''方法。

 
=== histogram ===
  '''im.histogram()''' => list

 返回图像的直方图。直方图是原图像中每一种像素值的个数的列表。如果图像有多于一个通道,那么所有通道的直方图被连接在一起。(比如,"RGB"图像的直方图包含768个值。)

  二值图像(模式"1")在这个方法中被作为灰度图像(模式"L")来处理。

 '''im.histogram(mask)''' => list

  返回图像中对应掩模图像是非零的那些像素的直方图。掩模图像必须和原图像同样大小,并且必须是二值图像(模式"1")或者灰度图像(模式"L")。

 
=== load ===
 '''im.load()'''

 分配图像数据的存储空间,并将数据从文件读入(或对于其它被推迟的操作,从源图像读入)。在通常情况下,你不需要调用这个方法。因为当被打开的图像第一次访问数据时,它会自动装入数据。

 
=== offset ===
 '''im.offset(xoffset, yoffset)''' => image

  (过期的)返回图像数据被平移给定的偏移量以后的图像。Data wraps around the edges. If yoffset is omitted, it is assumed to be equal to xoffset.

 这个方法以后将不被支持。新代码应该使用[imagechops.htm#offset ImageChops]模块提供的'''offset''' 函数。

 
=== paste ===
 '''im.paste(image, box)'''

Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). If a 4-tuple is given, the size of the pasted image must match the size of the region.

If the modes don't match, the pasted image is converted to the mode of this image (see the convert method for details).

'''im.paste(colour, box)'''

Same as above, but fills the region with a single colour. The colour is given as a single numerical value for single-band images, and a tuple for multi-band images.

'''im.paste(image, box, mask)'''

Same as above, but updates only the regions indicated by the mask. You can use either "1", "L" or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values can be used for transparency effects.

Note that if you paste an "RGBA" image, the alpha band is ignored. You can work around this by using the same image as both source image and mask.

'''im.paste(colour, box, mask)'''

Same as above, but fills the region indicated by the mask with a single colour.

=== point ===
  '''im.point(table)''' => image

'''im.point(function) image''' => image

Returns a copy of the image where each pixel has been mapped through the given table. The table should contains 256 values per band in the image. If a function is used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image.

If the image has mode "I" (integer) or "F" (floating point), you must use a function, and it must have the following format:

{{{
    argument * scale + offset }}}

'''Map floating point images''' {{{
    out = im.point(lambda i: i * 1.2 + 10) }}}

You can leave out either the '''scale''' or the ''' offset'''.

'''im.point(table, mode)''' => image

'''im.point(function, mode)''' => image

Map the image through table, and convert it on fly. In the current version of PIL , this can only be used to convert "L" and "P" images to "1" in one step, e.g. to threshold an image.

=== putalpha ===
  '''im.putalpha(band)'''

Copies the given band to the alpha layer of the current image. The image must be an "RGBA" image, and the band must be either "L" or "1".

=== putdata ===
 '''im.putdata(data)'''

'''im.putdata(data, scale, offset)'''

Copy pixel values from a sequence object into the image, starting at the upper left corner (0, 0). The scale and offset values are used to adjust the sequence values:

{{{
    pixel = value * scale + offset }}}

If the scale is omitted, it defaults to 1.0. If the offset is omitted, it defaults to 0.0.

=== putpalette ===
 '''im.putpalette(sequence)'''

Attach a palette to a "P" or "L" image. The palette sequence should contain 768 integer values, where each group of three values represent the red, green, and blue values for the corresponding pixel index. Instead of an integer sequence, you can use an 8-bit string.

=== putpixel ===
  '''im.putpixel(xy, colour)'''

Modifies the pixel at the given position. The colour is given as a single numerical value for single-band images, and a tuple for multi-band images.

Note that this method is relatively slow. For more extensive changes, use '''paste''' or the '''ImageDraw''' module instead.

=== resize ===
 '''im.resize(size)''' => image

'''im.resize(size, filter)''' => image

Returns a resized copy of an image. The size argument gives the requested size in pixels, as a 2-tuple: ('''width''', ''' height''').

The filter argument can be one of '''NEAREST''' (use nearest neighbour), '''BILINEAR''' (linear interpolation in a 2x2 environment), '''BICUBIC''' (cubic spline interpolation in a 4x4 environment), or '''ANTIALIAS''' (a high-quality downsampling filter). If omitted, or if the image has mode "1" or "P", it is set to '''NEAREST'''.

=== rotate ===
  '''im.rotate(angle)''' => image

'''im.rotate(angle, filter)''' => image

Returns a copy of an image rotated the given number of degrees counter clockwise around its centre.

The filter argument can be one of '''NEAREST''' (use nearest neighbour), '''BILINEAR''' (linear interpolation in a 2x2 environment), or '''BICUBIC''' (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to '''NEAREST'''.

=== save ===
  '''im.save(outfile, options)'''

'''im.save(outfile, format, options)'''

 用给定的文件名保存图像。如果format没有指定,将用文件扩展名来决定格式。这个方法返回None。

Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described later in this handbook.

You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the '''seek''', '''tell''', and '''write''' methods, and be opened in binary mode.

=== seek ===
 '''im.seek(frame)'''

Seeks to the given frame in a sequence file. If you seek beyond the end of the sequence, the method raises an '''EOFError''' exception. When a sequence file is opened, the library automatically seeks to frame 0.

Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.

=== show ===
 '''im.show()'''

 显示图像。这个方法主要用作调试目的。

 在Unix平台上,这个方法把图像保存为一个临时的PPM文件,然后调用'''xv''' 工具。

 在Windows平台上,它将图像保存为一个临时的BMP文件,并使用系统默认的BMP 显示工具来显示它(通常是'''Paint''')。

  这个方法返回None。

 
=== split ===
 '''im.split()''' => sequence

Returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue).

=== tell ===
 '''im.tell()''' => integer

  返回当前图像帧的序号。

 
=== thumbnail ===
 '''im.thumbnail(size)'''

'''im.thumbnail(size, filter)'''

Modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the ''' draft''' method to configure the file reader (where applicable), and finally resizes the image.

The filter argument can be one of '''NEAREST''', ''' BILINEAR''', '''BICUBIC''', or '''ANTIALIAS''' (best quality). If omitted, it defaults to '''NEAREST''' (this will be changed to ANTIALIAS in future versions).

Note that the bilinear and bicubic filters in the current version of PIL are not well-suited for thumbnail generation. You should use '''ANTIALIAS''' unless speed is much more important than quality.

Also note that this function modifies the Image object in place. If you need to use the full resolution image as well, apply this method to a '''copy''' of the original image. This method returns None.

=== tobitmap ===
  '''im.tobitmap()''' => string

Returns the image converted to an X11 bitmap.

=== tostring ===
 '''im.tostring()''' => string

Returns a string containing pixel data, using the standard "raw" encoder.

'''im.tostring(encoder, parameters)''' => string

Returns a string containing pixel data, using the given data encoding.

=== transform ===
 '''im.transform(size, method, data)''' => image

'''im.transform(size, method, data, filter)''' => image

 用给定的大小、与原图像相同的模式创建一个新图像,新图象的数据为原图像数据经过给定的变换而得到。

  在当前版本的PIL中,''method''参数可以是'''EXTENT'''(剪切一个矩形区域)、'''AFFINE'''(仿射变换)、'''QUAD'''(map a quadrilateral to a rectangle)或者'''MESH'''(map a number of source quadrilaterals in one operation)。不同的方法的区别如下。

  filter参数定义如何从源图像进行像素滤波得到目标像素。当前版本中这个参数可以是'''NEAREST'''(使用最近的像素),'''BILINEAR'''(使用2x2大小的双线性插值)、'''BICUBIC'''(使用4x4大小的三次样条插值)。如果这个参数省略,或者图像是"1"模式或者"P"模式的,这个参数将被设置成'''NEAREST'''。

  '''im.transform(size, EXTENT, data)''' => image

'''im.transform(size, EXTENT, data, filter)''' => image

 从图像中提取一个子区域。

 ''Data'' 是一个四元组 (''x0, y0, x1, y1''),指定输入图像上的两个点的坐标。结果图像将包含这两个点之间的数据,源图像上的 (''x0, y0'')成为目标图像上的 (0,0), 源图像上的(''x1, y1'')变成''size''。

  这个方法可以用来切割、拉伸、缩小或者镜像当前图像中的任意矩形区域。这个方法比'''crop'''稍慢,但是和对应的'''resize'''差不多快。

 '''im.transform(size, AFFINE, data)''' => image

'''im.transform(size, AFFINE, data, filter)''' => image

  对图像进行仿射变换,并把结果存在给定大小的图象中。

 ''Data'' 是一个6元组 (''a, b, c, d, e, f''),包含了仿射变换矩阵的前两行参数。对于结果图像上的每一个像素点 (''x, y''),像素值从源图像上的 (a ''x'' + b ''y'' + c, d ''x'' + e ''y'' + f)位置取得。

  这个函数可以用来对源图像进行缩放、平移、旋转和shear变换。

'''im.transform(size, QUAD, data)''' => image

'''im.transform(size, QUAD, data, filter)''' => image

 将图像上一个四边形 (有四个角定义的一个区域) 映射到一个给定大小的矩形中。

 ''Data'' 是一个8元组 (''x0, y0, x1, y1, x2, y2, y3, y3''),依次指定源图像上区域的左上角、左下角,右下角和右上角的坐标。

'''im.transform(size, MESH, data) image''' => image

'''im.transform(size, MESH, data, filter) image''' => image

 类似于'''QUAD''',只是data是一个目标矩形区域和对应源图像上的四边形的列表。

 
=== transpose ===
 '''im.transpose(method)''' => image

  返回一个原始图像镜像的或者旋转的图像。

 ''method'' 参数可以是:'''FLIP_LEFT_RIGHT'''、'''FLIP_TOP_BOTTOM'''、'''ROTATE_90'''、'''ROTATE_180'''或者'''ROTATE_270'''。

 
=== verify ===
  '''im.verify()'''

 使用这个函数来确定文件是否有损坏,但是并不对图像数据进行解码。如果这个函数发现问题,它将抛出异常。如果在使用这个函数后要读取图像数据,则必须重新打开这个图像文件。

 
== 属性 ==
'''Image''' 类的对象包含以下属性:

=== format ===
 '''im.format''' => string or None

  源文件的文件格式。如果是由库创建的图像,这个属性是None。

 
=== mode ===
 '''im.mode''' => string

 图像的模式。这是一个指定图像使用的像素格式的字符串。最常使用的模式是"1"、"L"、"RGB"以及"CMYK"。

 
=== size ===
 '''im.size''' => (width, height)

  图像的大小,以像素为单位。大小由一个二元组 (宽度, 高度)来表示。

 
=== palette ===
 '''im.palette''' => palette or None

 如果有调色板的话,这个属性指向颜色调色板。如果模式是"P", 它指向的是'''ImagePalette''' 类的一个对象。否则,它是 None。

 
=== info ===
  '''im.info''' => dictionary

 包含图像相关数据的字典。

Python Imaging Library 中文手册 (2003 版)

这是PIL的官方手册,2003年9月17日发布。这个版本涵盖 PIL 1.1.4的全部内容,同时也包括部分1.1.5新增的内容。

原版出处:http://www.pythonware.com/library/pil/handbook/

TableOfContents

Python Imaging Library 概述

  • PIL 1.1.4 | 2003年9月17日 | Fredrik Lundh, Matthew Ellis

1. 介绍

  • Python Imaging Library 为Python解释器提供了图像处理的功能。

这个库提供了广泛的文件格式支持、高效的内部表示以及相当强大的图像处理功能。 图像处理库的核心被设计成能够快速访问以几种基本像素类型表示的图像数据。它为通用图像处理工具提供了一个坚实基础。 让我们来看一些这个库的用途:

2. 图像归档处理

  • Python Imaging Library适合编写图像归档和批处理应用程序。使用这个库可以创建缩略图、转换文件格式、打印图像等。

当前版本的库能够识别和读取大量的图像格式。而能够输出的格式被特意限制在一些最常用以交换和展示的格式上。

3. 图像显示

  • 当前版本的库包括Tk的PhotoImage BitmapImage 接口,也包括Windows的DIB接口(需要同PythonWin一起使用)。对于在X和Mac上显示,可以使用Jack Jansen的img 库。

为了调试方便,Unix版本的库提供了一个 show 方法,它会调用 xv 来显示图像。

4. 图像处理

  • 这个库提供了基本的图像处理功能,包括点操作、内建滤波核滤波操作以及颜色空间变换操作。

这个库也支持图像的缩放、旋转及任何仿射(affine)变换。 库中包含一个直方图方法,可以从图像中提取某些统计特征。用它可以实现自动的对比度增强以及全局统计分析功能。

入门导引

1. 使用 Image 类

Python Imaging Library中最重要的类是Image 类,定义在与它同名的模块中。有多种创建这个类的对象的方法:或者从文件中读取得到,或者从其他图像经处理得到,或者从头创建。

要从文件读取图像,可以使用Image 模块提供的open 函数。

   1 >>> import Image
   2 >>> im = Image.open("lena.ppm")

如果成功,这个函数返回一个Image 对象。可以使用这个对象的属性来检查文件的内容。

   1 >>> print im.format, im.size, im.mode
   2 PPM (512, 512) RGB

format 属性表示图像的原始格式。如果图像不是从文件中读取的,则它被设置成 None。size 属性是一个2-tuple,表示图像的宽度和高度 (以像素为单位)。mode 属性定义图像的通道的数量与名字,同时也包括像素的类型和颜色深度信息。通常来说,灰度图像的mode是"L" (luminance),真彩色图像的mode是 "RGB" ,pre-press图像的mode是"CMYK"。

如果文件不能打开,会抛出一个IOError 异常。

如果已经创建好了一个Image 类的对象,接下来就可以使用这个类定义的方法来处理和操作图像了。比如说,显示刚才打开的文件:

   1     >>> im.show()

(show 的标准实现不是很高效,它先将图像保存成一个临时文件,然后调用 xv 程序来显示图像。如果你没有安装xv ,它甚至不能工作。然而如果它可用,它将是非常方便的测试和除错的工具。)

接下来的内容将对库中提供的一些功能进行一个概述。

2. 读写图像

Python Imaging Library 支持很广泛的图象文件格式。要从磁盘上读取文件,使用 Image 模块提供的open 函数。你不必了解你要打开的文件的格式,库会自动根据文件的内容来确定图像的格式。

要保存文件,使用Image 类的save 方法。保存文件时,文件名是非常重要的。除非你制定了格式,否则库会根据文件扩展名来决定使用哪种格式存储。

2.1. 将文件转换成 JPEG

   1 import os, sys
   2 import Image
   3 
   4 for infile in sys.argv[1:]:
   5     f, e = os.path.splitext(infile)
   6     outfile = f + ".jpg"
   7     if infile != outfile:
   8         try:
   9             Image.open(infile).save(outfile)
  10         except IOError:
  11             print "cannot convert", infile

save 方法可以带第二个参数,用来显式指定文件的格式。如果要使用非标准的扩展名,就必须这样指定文件格式:

2.2. 创建 JPEG 缩略图

   1 import os, sys
   2 import Image
   3 
   4 size = 128, 128
   5 
   6 for infile in sys.argv[1:]:
   7     outfile = os.path.splitext(infile)[0] + ".thumbnail"
   8     if infile != outfile:
   9         try:
  10             im = Image.open(infile)
  11             im.thumbnail(size)
  12             im.save(outfile, "JPEG")
  13         except IOError:
  14             print "cannot create thumbnail for", infile

有一点非常重要的需要注意的是,除非到了迫不得已的时候,库不会装载或者解码光栅数据。当打开一个文件的时候,库会读取文件头以获得文件格式、颜色模式、图像大小等属性,但是文件剩余的部分不会马上处理。

这意味着,文件打开操作是很快的,它与文件的大小、压缩的类型没有关系。这里是一个快速识别一系列图像文件的简单例子:

2.3. 识别图像文件

   1 import sys
   2 import Image
   3 
   4 for infile in sys.argv[1:]:
   5     try:
   6         im = Image.open(infile)
   7         print infile, im.format, "%dx%d" % im.size, im.mode
   8     except IOError:
   9         pass

3. 裁剪、粘贴和合并图像

Image 类提供一些对图像中的区域进行处理的方法。要从图像中提取一块子矩形区域,使用 crop 方法。

3.1. 从图像中拷贝一块子矩形区域

   1     box = (100, 100, 400, 400)
   2     region = im.crop(box)

区域由4元组定义,表示为 (left, upper, right, lower)。 Python Imaging Library 使用左上角为 (0, 0)的坐标系统。同时要注意,坐标指向像素之间的位置,因此上述例子中描述的区域的大小为300x300像素。

区域图像能够经过某些特定的处理并粘回原处。

3.2. 处理一块子矩形区域,并粘回原处

   1     region = region.transpose(Image.ROTATE_180)
   2     im.paste(region, box)

当把区域粘回原处时,指定的区域大小必须和区域图像的大小相同。此外,区域不能超出图像的边界。然而,原始图像的模式和区域图像的模式不必相同。如果不相同,区域图像的模式在粘贴时会被自动转换 (细节请查看后面有关颜色变换 的章节)。

这里有另一个例子:

3.3. 滚动一幅图像

   1 def roll(image, delta):
   2     "Roll an image sideways"
   3 
   4     xsize, ysize = image.size
   5 
   6     delta = delta % xsize
   7     if delta == 0: return image
   8 
   9     part1 = image.crop((0, 0, delta, ysize))
  10     part2 = image.crop((delta, 0, xsize, ysize))
  11     image.paste(part2, (0, 0, xsize-delta, ysize))
  12     image.paste(part1, (xsize-delta, 0, xsize, ysize))
  13 
  14     return image

更高级的技巧是,paste方法可以带一个透明掩模作为可选参数。在这个掩模中,像素值255 代表被粘贴的图像在那个位置上是不透明的。 (就是说,此处显示被粘贴的图像上的值。)像素值 0 表示被粘贴的图像是完全透明的。在它们之间的值表示不同程度的透明度。

Python Imaging Library 还允许对一幅多通道图像(比如RGB图像)的单个通道进行操作。split方法能够创建一组新的图像,每一幅都是原来多通道图像的一个通道。merge函数以一个模式和一组图像的元组为参数,把这些图像组成一幅新图像。下面的例子实现交换一幅RGB图像的三个通道:

3.4. 分离与合并通道

   1 r, g, b = im.split()
   2 im = Image.merge("RGB", (b, g, r))

4. 几何变换

Image 类包含resize 和 rotate 方法来缩放和旋转图像。前者带一个tuple类型的参数来表示新的图像大小,后者带一个逆时针旋转的角度值作为参数。

4.1. 简单的几何变换

   1 out = im.resize((128, 128))
   2 out = im.rotate(45) # degrees counter-clockwise

如果要将图像旋转90度的整数倍,可以使用rotate 或者transpose 方法。后者还可以用来水平或者垂直镜像一幅图像。

4.2. transpose图像

   1 out = im.transpose(Image.FLIP_LEFT_RIGHT)
   2 out = im.transpose(Image.FLIP_TOP_BOTTOM)
   3 out = im.transpose(Image.ROTATE_90)
   4 out = im.transpose(Image.ROTATE_180)
   5 out = im.transpose(Image.ROTATE_270)

There's no difference in performance or result between transpose(ROTATE) and corresponding rotate operations.

一个更通用的变换方法是 transform,在参考手册中有对它的详细叙述。

5. 颜色变换

Python Imaging Library提供convert函数,可以将图像在不同的像素格式间转换。

5.1. 转换图像颜色模式

   1     im = Image.open("lena.ppm").convert("L")

库支持在所有支持的颜色模式和"L"以及"RGB"之间的直接转换。其他颜色模式之间的转换要借助于中间图像模式(通常是"RGB" 模式)。

6. 图像增强

Python Imaging Library提供一系列的函数和模块来进行图像增强。

6.1. 滤波器

ImageFilter 模块中包含一些预定义的增强滤波器,用filter 方法来使用滤波器。

6.1.1. 使用滤波器

   1 import ImageFilter
   2 out = im.filter(ImageFilter.DETAIL)

6.2. 点操作

point 方法可以对图像的像素值进行变换(比如对比度变换)。在大多数场合,使用函数对象(带一个参数)作为参数传递给point方法。每一个像素使用这个函数对象进行变换:

6.2.1. 使用点变换

   1 # multiply each pixel by 1.2
   2 out = im.point(lambda i: i * 1.2)

用上面的技巧,你可以对图像用任何简单的表达式进行变换。你还可以结合使用point 和paste 方法来有选择的改变一幅图像:

6.2.2. 处理单个通道

   1 # split the image into individual bands
   2 source = im.split()
   3 
   4 R, G, B = 0, 1, 2
   5 
   6 # select regions where red is less than 100
   7 mask = source[R].point(lambda i: i < 100 and 255)
   8 
   9 # process the green band
  10 out = source[G].point(lambda i: i * 0.7)
  11 
  12 # paste the processed band back, but only where red was < 100
  13 source[G].paste(out, None, mask)
  14 
  15 # build a new multiband image
  16 im = Image.merge(im.mode, source)

注意用来创建mask的语法:

   1     imout = im.point(lambda i: expression and 255)

Python 只计算一个逻辑表达式的一部分,只要能确定表达式的结果其他部分就不进行计算了,并把最后计算得到的值作为表达式的值返回。因此,如果上述expression是false(0),Python就不会检查第二个参数,因此返回0,否则返回255。

6.3. 增强

对于更多更高级的图像增强,可以使用ImageEnhance 模块。一旦从图像上创建了增强对象,你就可以尝试采用各种不同的参数进行快速的增强处理了。

你能通过这样的方法来调整图像的对比度、亮度、色彩平衡和锐度。

6.3.1. 增强图像

   1 import ImageEnhance
   2 
   3 enh = ImageEnhance.Contrast(im)
   4 enh.enhance(1.3).show("30% more contrast")

7. 图像序列

Python Imaging Library 包含对于图像序列 (也称作动画 格式)的基本支持。支持的序列格式包括 FLI/FLC, GIF, 和一些试验性的格式。TIFF 文件也能包含超过一帧的图像。

当你打开一个序列文件时,PIL 会自动加载序列中的第一帧。你可以使用seek 和tell 方法在不同帧之间移动:

7.1. 读取图像序列

   1 import Image
   2 
   3 im = Image.open("animation.gif")
   4 im.seek(1) # skip to the second frame
   5 
   6 try:
   7     while 1:
   8         im.seek(im.tell()+1)
   9         # do something to im
  10 except EOFError:
  11     pass # end of sequence

正如这个例子所示,当序列结束时,你会得到一个EOFError 异常。

注意,当前版本库的绝大多数驱动只允许你移动到下一帧(如上面例子所示)。如果要回到文件的开头,你可能必须重新打开它。

下面的迭代类让你能够使用for循环来迭代图像序列:

7.2. 一个序列迭代类

   1 class ImageSequence:
   2     def __init__(self, im):
   3         self.im = im
   4     def __getitem__(self, ix):
   5         try:
   6             if ix:
   7                 self.im.seek(ix)
   8             return self.im
   9         except EOFError:
  10             raise IndexError # end of sequence
  11 
  12 for frame in ImageSequence(im):
  13     # ...do something to frame...

8. Postscript格式打印

Python Imaging Library提供将图像、文字和图形输出到Postscript打印机的功能。这是一个简单的例子:

8.1. Drawing Postscript

   1 import Image
   2 import PSDraw
   3 
   4 im = Image.open("lena.ppm")
   5 title = "lena"
   6 box = (1*72, 2*72, 7*72, 10*72) # in points
   7 
   8 ps = PSDraw.PSDraw() # default is sys.stdout
   9 ps.begin_document(title)
  10  
  11 # draw the image (75 dpi)
  12 ps.image(box, im, 75)
  13 ps.rectangle(box) 
  14 
  15 # draw centered title
  16 ps.setfont("HelveticaNarrow-Bold", 36)
  17 w, h, b = ps.textsize(title)
  18 ps.text((4*72-w/2, 1*72-h), title) 
  19 
  20 ps.end_document()

9. 更多关于读取图像

前面叙述过,Image模块的open函数用来打开一个图像文件。在大多数情况,你只用简单的把文件名传给它就可以了:

   1 im = Image.open("lena.ppm")

如果一切正常,结果是一个Image 对象。否则,会抛出一个IOError 异常。

你可以使用一个类似文件的对象来代替文件名。这个对象必须实现read、 seek 和 tell 方法,并以二进制方式打开。 从一个打开的文件读取

   1 fp = open("lena.ppm", "rb")
   2 im = Image.open(fp)

要从字符串数据中读取一幅图像,可以使用StringIO 类: 从一个字符串读取

   1 import StringIO
   2 
   3 im = Image.open(StringIO.StringIO(buffer))

注意库在读取图像头之前,会先移动到文件头 (用seek(0))。另外,在图像数据被读取 (通过 load 方法)以后,seek方法也会被调用。如果图像文件被嵌在一个更大的文件里面,比如tar文件,你可以使用ContainerIO 或者TarIO 模块来访问它。 从一个tar压缩文档读取

   1 import TarIO
   2 
   3 fp = TarIO.TarIO("Imaging.tar", "Imaging/test/lena.ppm")
   4 im = Image.open(fp)

9.1. 控制解码器

一些解码器允许你在从文件读取图像的同时对图像进行操作。这个特性常常被用来在创建缩略图(创建缩略图的速度通常比缩略图的质量更重要)或者打印到一个黑白激光打印机(只需要图像的灰度信息)时加速图像的解码。

draft 方法能够操作一个没有被载入数据的图像对象,使得它能够尽可能与需要的模式和大小相匹配。这通过重新配置图像解码器来实现。 以草稿方式读取

   1 im = Image.open(file)
   2 print "original =", im.mode, im.size
   3 
   4 im.draft("L", (100, 100))
   5 print "draft =", im.mode, im.size

这个程序可能会打印出这样的结果:

   1 original = RGB (512, 512)
   2 draft = L (128, 128)

注意,最终获得图像可能与要求的模式和大小不完全一致。如果要求生成的图像不能超过给定的大小,可以使用thumbnail方法来代替。

概念

  • Python Imaging Library 处理光栅图像(raster images),即方型的像素数据。

1. 通道

一幅图像可以有一个或者多个通道的数据构成。Python Imaging Library允许在一个图像中存储多个通道,只要这些通道的大小和颜色深度都是一样的。

要获取图像的通道数目和通道名称,可以使用[image.htm#image-getbands-method getbands] 方法。

2. 模式

图像的模式定义了图像的像素的类型和颜色深度。当前版本的库支持下列标准模式:

  • 1 (1-bit 像素, 黑白, 一个像素存储为一个字节)

  • L (8-bit 像素, 黑白)

  • P (8-bit 像素, 使用调色板映射到其他任一模式)

  • RGB (3x8-bit 像素, 真彩色)

  • RGBA (4x8-bit 像素, 带透明掩模的真彩色)

  • CMYK (4x8-bit 像素, colour separation)

  • YCbCr (3x8-bit 像素, colour video format)

  • I (32-bit integer 像素)

  • F (32-bit floating point 像素)

PIL 还支持一些特殊的模式,包括RGBX (true colour with padding)和RGBa (true colour with premultiplied alpha)。

你可以通过[image.htm#image-mode-attribute mode]属性读取图像的模式,它是一个包含上述模式类型值的字符串。

3. 大小

通过图像的[image.htm#image-size-attribute size]属性可以读取图像的大小信息。大小信息由一个包含水平和垂直像素数的二元组表示。

4. 坐标系统

Python Imaging Library 使用笛卡尔像素坐标系统,原点 (0,0)在图像的左上角。 注意:坐标值对应像素的左上角,像素(0, 0)实际中心位于(0.5, 0.5)。

坐标通常以2元组(x, y)的形式传递给库。矩形则表示成4元组的形式,左上角为第一个。比如,覆盖整个800x600像素的矩形表示为(0, 0, 800, 600)。

5. 调色板

调色板模式 ("P")使用一个彩色调色板来定义每个像素的真实颜色。

6. 信息

你可以使用[image.htm#image-info-attribute info]属性在图像中添加辅助的信息。这是一个字典对象。

在读取和存储文件时如何处理这些信息是和文件的类型有关系的(查看[formats.htm 图像文件格式]这一章)。

7. 滤波器

对于将多个输入像素映射到一个输出像素的几何变换操作,Python Imaging Library 提供了四种重采用滤波器

* NEAREST
在输入图像中选择最近的点,忽略其他所有点。
* BILINEAR
在输入图像的2x2像素范围内进行线性插值。注意当前版本的PIL中,这个滤波器在下采样时使用固定的输入范围的大小。
* BICUBIC
在输入图像的4x4像素范围内进行三次插值。注意当前版本的PIL中,这个滤波器在下采样时使用固定的输入范围的大小。
* ANTIALIAS

(在PIL 1.1.3中新增)。 使用高质量的重采样滤波器(a truncated sinc)对所有可能影响结果的输入像素进行计算来得到输出像素的值。在当前版本的PIL中,这个滤波器只能在resize thumbnail 方法中使用。

注意,当前版本的PIL中,只有ANTIALIAS滤波器是唯一在下采样(把一幅较大的图像转换成较小的图像)时能正常工作的滤波器。BILINEAR和BICUBIC滤波器使用固定的输入范围大小,适用在保持比例(scale-preserving?)的几何转换或者上采样时。

Image 模块

Image 模块提供了一个同名的类,用来表示一个PIL图像。这个模块同时提供了一些工厂函数,包括从文件读取图像的函数以及创建新图像的函数。

1. 例子

下面的脚本读取一幅图像,旋转45度,再把它在Unix上用xv显示出来,或者在Windows上用paint显示出来。

打开、旋转、显示图像 (使用默认的图像浏览器)

 import Image im = Image.open("bride.jpg") im.rotate(45).show() 
  • 下面的脚本创建当前目录中所有JPEG图像的128x128的缩略图。创建缩略图

    import glob  for infile in glob.glob("*.jpg"):     file, ext = os.path.splitext(infile)     im = Image.open(infile)     im.thumbnail((128, 128), Image.ANTIALIAS)     im.save(file + ".thumbnail", "JPEG") 

2. 函数

2.1. new

  • Image.new(mode, size) => image

Image.new(mode, size, color) => image

  • 使用给定的模式和大小创建一个新图像。大小是以2元组的形式给出的。 当创建单通道的图时,color是单个值;当创建多通道图像时,color是一个元组(每个通道一个值)。如果color参数缺省,图像被填充成全黑。如果color是None,则图像不被初始化。

2.2. open

  • Image.open(infile) => image

Image.open(infile, mode) => image

  • 打开并识别给定的图像文件。这是一个会被延迟(lazy)的操作;实际的图像数据并不马上从文件中读入,而是等到需要处理这些数据的时候才被读入 (可以调用load 方法强制读入数据)。如果要指定mode参数,则mode必须是"r"。

    • 你可以使用一个字符串(表示文件名)或者一个文件对象作为infile。在用文件对象时,文件对象必须实现read, seek, 和tell 方法,而且必须用二进制模式打开。

2.3. blend

  • Image.blend(image1, image2, alpha) => image

    • 对两幅图像用固定的透明度(alpha)插值生成新的图像。输入的两幅图像必须是同样的大小和模式。
        out = image1 * (1.0 - alpha) + image2 * alpha 
    如果alpha是0.0,则会返回第一幅图像的一个拷贝。如果alpha是1.0,则会返回第二幅图像的一个拷贝。alpha的取值范围没有限制。如果必要,计算结果会被裁减到允许的输出值的范围。

2.4. composite

  • Image.composite(image1, image2, mask) => image 对两幅图像用图像mask作为透明度插值生成新的图像。 mask图像可以是"1", "L", 或者"RGBA"模式。所有的图像必须是同样的大小。

2.5. eval

  • Image.eval(function, image) => image 将函数(应该带一个参数)作用于给定图像的每一个像素。如果图像有多个通道,这个函数会作用于每一个通道。注意,这个函数对于同样的像素值只会被调用一次,因此你不能使用一个随机函数或者其它的像素生成函数来作为函数。

2.6. frombuffer

  • Image.frombuffer(mode, size, data) => image

    (PIL 1.1.4 alpha 4中新增。) 对字符串或者缓冲区对象包含的像素数据,使用标准的"raw"解码器来创建图像。。对于某些模式,图像内存可以与原始缓冲区共享同一块内存 (这意味着如果修改原始的缓冲区对象,将会对图像产生影响)。不是所有的模式都能够共享内存;支持的模式包括"L"、"RGBX"、"RGBA"和"CMYK"。对于其他模式,这个函数和fromstring函数作用相同。

    Image.frombuffer(mode, size, data, decoder, parameters) => image

    与对应的fromstring 函数调用相同。

2.7. fromstring

  • Image.fromstring(mode, size, data) => image 从字符串中读取像素数据,使用标准的"raw"解码器创建图像。

    Image.fromstring(mode, size, data, decoder, parameters) => image

    • 与前一个函数的区别是,这个函数允许使用你使用任意PIL支持的像素解码器来解码数据。更多有关解码器的信息,参看[decoder.htm 编写自己的文件解码器]。

    注意,这个函数只是解码像素数据,而不是解码整个图像。如果要处理存在字符串中的完整图像,可以使用StringIO把字符串包装起来然后用[#image-open-function open]方法来装载它。

2.8. merge

  • Image.merge(mode, bands) => image

    • 从一组单通道的图像创建一幅新图像。通道用图像的元组或者列表的形式给出,每一项是模式mode描述的一个通道。所有通道的大小必须相同。

3. 方法

Image 类的对象有下列方法。除非特别声明,所有的方法返回一个新的Image类型对象,包含处理的结果。

3.1. convert

  • im.convert(mode) => image

    • 返回转换后的图象拷贝。对于"P"模式,这种转换通过调色板进行。如果模式被省略,那么该方法会自动选取一个能够保存所有图像信息和不需要调色板来表示的图像模式。
    当前版本的库支持"L"、"RGB"和"CMYK"模式之间的相互转换。 当把一幅彩色图像转换成灰度图象(模式"L"),库使用 ITU-R 601-2两度转换公式:
        L = R * 299/1000 + G * 587/1000 + B * 114/1000 

    当把一幅灰度图象转换成2值图像(模式"1")时,所有非零值都被转换成255(白)。要使用其它阈值,可以使用point方法。

    • im.convert(mode, matrix) => image

    将"RGB"模式图像使用一个转换矩阵转换成"RGB"或者"L"模式图像。矩阵是一个四元组或者16元组。 下面的例子将RGB图像 (根据 ITU-R 709使用 D65 亮度进行过线性校正) 转换成 CIE XYZ颜色空间图像:

    Convert RGB to XYZ

        rgb2xyz = (         0.412453, 0.357580, 0.180423, 0,         0.212671, 0.715160, 0.072169, 0,         0.019334, 0.119193, 0.950227, 0 )     out = im.convert("RGB", rgb2xyz) 

3.2. copy

  • im.copy() => image 拷贝图像。使用这个函数把其它东西粘贴到图像中,并保留原来的图像不变。

3.3. crop

  • im.crop(box) => image

    • 返回当前图像的一个矩形区域。box 是一个四元组指定左、上、右、下四个边界的坐标。

    这是一个会被延迟(lazy)的操作。改变原始的图像可能会影响到剪裁生成的图像。为消除这种影响,可以调用裁剪生成的图象的load方法。

3.4. draft

  • im.draft(mode, size) 配置图像装载器使其能够返回与指定模式尽可能接近的图像。比如说,你可以使用这个函数,将彩色JPEG图像在装载的时候转换成灰度图象,或者从PCD文件中解出128x192的图像。 注意,这个方法会改变调用的Image对象。如果图像已经被装入,这个方法没有任何作用。

3.5. filter

  • im.filter(filter) => image

    • 返回当前图像经过给定滤波器滤波后的图像。 要查看可用的滤波器,参考ImageFilter 模块。

3.6. fromstring

  • im.fromstring(data)

im.fromstring(data, decoder, parameters)

  • fromstring函数基本相同,只是将data装入当前图像。

3.7. getbands

  • im.getbands() => tuple of strings

    • 返回包含每个通道的名字的元组。比如,在RGB图像上调用getbands返回("R", "G", "B")。

3.8. getbbox

  • im.getbbox() => 4-tuple or None

Calculates the bounding box of the non-zero regions in the image. The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. If the image is completely empty, this method returns None.

3.9. getdata

  • im.getdata() => sequence

    • 返回以像素值序列的形式返回当前图像的内容。图像的像素值从第零行开始被一行一行的连接在一起变成一维线性的序列对象。

    注意,这个方法返回的序列对象是PIL内部数据类型,只支持部分序列操作。可以使用 list(im.getdata())将其转换为普通的序列对象(比如需要打印)。

3.10. getextrema

  • im.getextrema() => 2-tuple 返回一个二元组包含图像的最小值和最大值。当前版本的PIL中这个方法仅支持单通道图像。

3.11. getpixel

  • im.getpixel(xy) => value or tuple 返回指定位置的像素值。如果图像是多层(multi-layer)图像,该方法返回一个元组。

    注意,这个方法相当慢;如果你需要处理大量的图像数据,使用getdata方法。

3.12. histogram

  • im.histogram() => list

  • 返回图像的直方图。直方图是原图像中每一种像素值的个数的列表。如果图像有多于一个通道,那么所有通道的直方图被连接在一起。(比如,"RGB"图像的直方图包含768个值。)
    • 二值图像(模式"1")在这个方法中被作为灰度图像(模式"L")来处理。

    im.histogram(mask) => list

    • 返回图像中对应掩模图像是非零的那些像素的直方图。掩模图像必须和原图像同样大小,并且必须是二值图像(模式"1")或者灰度图像(模式"L")。

3.13. load

  • im.load() 分配图像数据的存储空间,并将数据从文件读入(或对于其它被推迟的操作,从源图像读入)。在通常情况下,你不需要调用这个方法。因为当被打开的图像第一次访问数据时,它会自动装入数据。

3.14. offset

  • im.offset(xoffset, yoffset) => image

    • (过期的)返回图像数据被平移给定的偏移量以后的图像。Data wraps around the edges. If yoffset is omitted, it is assumed to be equal to xoffset.

    这个方法以后将不被支持。新代码应该使用[imagechops.htm#offset ImageChops]模块提供的offset 函数。

3.15. paste

  • im.paste(image, box)

Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). If a 4-tuple is given, the size of the pasted image must match the size of the region.

If the modes don't match, the pasted image is converted to the mode of this image (see the convert method for details).

im.paste(colour, box)

Same as above, but fills the region with a single colour. The colour is given as a single numerical value for single-band images, and a tuple for multi-band images.

im.paste(image, box, mask)

Same as above, but updates only the regions indicated by the mask. You can use either "1", "L" or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values can be used for transparency effects.

Note that if you paste an "RGBA" image, the alpha band is ignored. You can work around this by using the same image as both source image and mask.

im.paste(colour, box, mask)

Same as above, but fills the region indicated by the mask with a single colour.

3.16. point

  • im.point(table) => image

im.point(function) image => image

Returns a copy of the image where each pixel has been mapped through the given table. The table should contains 256 values per band in the image. If a function is used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image.

If the image has mode "I" (integer) or "F" (floating point), you must use a function, and it must have the following format:

    argument * scale + offset 

Map floating point images

    out = im.point(lambda i: i * 1.2 + 10) 

You can leave out either the scale or the offset.

im.point(table, mode) => image

im.point(function, mode) => image

Map the image through table, and convert it on fly. In the current version of PIL , this can only be used to convert "L" and "P" images to "1" in one step, e.g. to threshold an image.

3.17. putalpha

  • im.putalpha(band)

Copies the given band to the alpha layer of the current image. The image must be an "RGBA" image, and the band must be either "L" or "1".

3.18. putdata

  • im.putdata(data)

im.putdata(data, scale, offset)

Copy pixel values from a sequence object into the image, starting at the upper left corner (0, 0). The scale and offset values are used to adjust the sequence values:

    pixel = value * scale + offset 

If the scale is omitted, it defaults to 1.0. If the offset is omitted, it defaults to 0.0.

3.19. putpalette

  • im.putpalette(sequence)

Attach a palette to a "P" or "L" image. The palette sequence should contain 768 integer values, where each group of three values represent the red, green, and blue values for the corresponding pixel index. Instead of an integer sequence, you can use an 8-bit string.

3.20. putpixel

  • im.putpixel(xy, colour)

Modifies the pixel at the given position. The colour is given as a single numerical value for single-band images, and a tuple for multi-band images.

Note that this method is relatively slow. For more extensive changes, use paste or the ImageDraw module instead.

3.21. resize

  • im.resize(size) => image

im.resize(size, filter) => image

Returns a resized copy of an image. The size argument gives the requested size in pixels, as a 2-tuple: (width, height).

The filter argument can be one of NEAREST (use nearest neighbour), BILINEAR (linear interpolation in a 2x2 environment), BICUBIC (cubic spline interpolation in a 4x4 environment), or ANTIALIAS (a high-quality downsampling filter). If omitted, or if the image has mode "1" or "P", it is set to NEAREST.

3.22. rotate

  • im.rotate(angle) => image

im.rotate(angle, filter) => image

Returns a copy of an image rotated the given number of degrees counter clockwise around its centre.

The filter argument can be one of NEAREST (use nearest neighbour), BILINEAR (linear interpolation in a 2x2 environment), or BICUBIC (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to NEAREST.

3.23. save

  • im.save(outfile, options)

im.save(outfile, format, options)

  • 用给定的文件名保存图像。如果format没有指定,将用文件扩展名来决定格式。这个方法返回None。

Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described later in this handbook.

You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the seek, tell, and write methods, and be opened in binary mode.

3.24. seek

  • im.seek(frame)

Seeks to the given frame in a sequence file. If you seek beyond the end of the sequence, the method raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame 0.

Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.

3.25. show

  • im.show() 显示图像。这个方法主要用作调试目的。

    在Unix平台上,这个方法把图像保存为一个临时的PPM文件,然后调用xv 工具。

    在Windows平台上,它将图像保存为一个临时的BMP文件,并使用系统默认的BMP 显示工具来显示它(通常是Paint)。

    • 这个方法返回None。

3.26. split

  • im.split() => sequence

Returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue).

3.27. tell

  • im.tell() => integer

    • 返回当前图像帧的序号。

3.28. thumbnail

  • im.thumbnail(size)

im.thumbnail(size, filter)

Modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the draft method to configure the file reader (where applicable), and finally resizes the image.

The filter argument can be one of NEAREST, BILINEAR, BICUBIC, or ANTIALIAS (best quality). If omitted, it defaults to NEAREST (this will be changed to ANTIALIAS in future versions).

Note that the bilinear and bicubic filters in the current version of PIL are not well-suited for thumbnail generation. You should use ANTIALIAS unless speed is much more important than quality.

Also note that this function modifies the Image object in place. If you need to use the full resolution image as well, apply this method to a copy of the original image. This method returns None.

3.29. tobitmap

  • im.tobitmap() => string

Returns the image converted to an X11 bitmap.

3.30. tostring

  • im.tostring() => string

Returns a string containing pixel data, using the standard "raw" encoder.

im.tostring(encoder, parameters) => string

Returns a string containing pixel data, using the given data encoding.

3.31. transform

  • im.transform(size, method, data) => image

im.transform(size, method, data, filter) => image

  • 用给定的大小、与原图像相同的模式创建一个新图像,新图象的数据为原图像数据经过给定的变换而得到。
    • 在当前版本的PIL中,method参数可以是EXTENT(剪切一个矩形区域)、AFFINE(仿射变换)、QUAD(map a quadrilateral to a rectangle)或者MESH(map a number of source quadrilaterals in one operation)。不同的方法的区别如下。

      filter参数定义如何从源图像进行像素滤波得到目标像素。当前版本中这个参数可以是NEAREST(使用最近的像素),BILINEAR(使用2x2大小的双线性插值)、BICUBIC(使用4x4大小的三次样条插值)。如果这个参数省略,或者图像是"1"模式或者"P"模式的,这个参数将被设置成NEAREST

      im.transform(size, EXTENT, data) => image

im.transform(size, EXTENT, data, filter) => image

  • 从图像中提取一个子区域。

    Data 是一个四元组 (x0, y0, x1, y1),指定输入图像上的两个点的坐标。结果图像将包含这两个点之间的数据,源图像上的 (x0, y0)成为目标图像上的 (0,0), 源图像上的(x1, y1)变成size

    • 这个方法可以用来切割、拉伸、缩小或者镜像当前图像中的任意矩形区域。这个方法比crop稍慢,但是和对应的resize差不多快。

    im.transform(size, AFFINE, data) => image

im.transform(size, AFFINE, data, filter) => image

  • 对图像进行仿射变换,并把结果存在给定大小的图象中。
  • Data 是一个6元组 (a, b, c, d, e, f),包含了仿射变换矩阵的前两行参数。对于结果图像上的每一个像素点 (x, y),像素值从源图像上的 (a x + b y + c, d x + e y + f)位置取得。

    • 这个函数可以用来对源图像进行缩放、平移、旋转和shear变换。

im.transform(size, QUAD, data) => image

im.transform(size, QUAD, data, filter) => image

  • 将图像上一个四边形 (有四个角定义的一个区域) 映射到一个给定大小的矩形中。

    Data 是一个8元组 (x0, y0, x1, y1, x2, y2, y3, y3),依次指定源图像上区域的左上角、左下角,右下角和右上角的坐标。

im.transform(size, MESH, data) image => image

im.transform(size, MESH, data, filter) image => image

  • 类似于QUAD,只是data是一个目标矩形区域和对应源图像上的四边形的列表。

3.32. transpose

  • im.transpose(method) => image

    • 返回一个原始图像镜像的或者旋转的图像。

    method 参数可以是:FLIP_LEFT_RIGHTFLIP_TOP_BOTTOMROTATE_90ROTATE_180或者ROTATE_270

3.33. verify

  • im.verify()

  • 使用这个函数来确定文件是否有损坏,但是并不对图像数据进行解码。如果这个函数发现问题,它将抛出异常。如果在使用这个函数后要读取图像数据,则必须重新打开这个图像文件。

4. 属性

Image 类的对象包含以下属性:

4.1. format

  • im.format => string or None

    • 源文件的文件格式。如果是由库创建的图像,这个属性是None。

4.2. mode

  • im.mode => string 图像的模式。这是一个指定图像使用的像素格式的字符串。最常使用的模式是"1"、"L"、"RGB"以及"CMYK"。

4.3. size

  • im.size => (width, height)

    • 图像的大小,以像素为单位。大小由一个二元组 (宽度, 高度)来表示。

4.4. palette

  • im.palette => palette or None

    如果有调色板的话,这个属性指向颜色调色板。如果模式是"P", 它指向的是ImagePalette 类的一个对象。否则,它是 None。

4.5. info

  • im.info => dictionary

  • 包含图像相关数据的字典。

PythonImageLibrary中文手册 (2008-02-23 15:35:12由localhost编辑)

ch3n2k.com | Copyright (c) 2004-2020 czk.