发布于 2015-09-11 16:15:37 | 1121 次阅读 | 评论: 0 | 来源: 网络整理
The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
The following script loads an image, rotates it 45 degrees, and displays it using an external viewer (usually xv on Unix, and the paint program on Windows).
from PIL import Image
im = Image.open("bride.jpg")
im.rotate(45).show()
The following script creates nice 128x128 thumbnails of all JPEG images in the current directory.
from PIL import Image
import glob, os
size = 128, 128
for infile in glob.glob("*.jpg"):
file, ext = os.path.splitext(infile)
im = Image.open(infile)
im.thumbnail(size, Image.ANTIALIAS)
im.save(file + ".thumbnail", "JPEG")
Opens and identifies the given image file.
This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method). See new().
参数: | |
---|---|
返回: | An Image object. |
引发 IOError: | If the file cannot be found, or the image cannot be opened and identified. |
Alpha composite im2 over im1.
参数: |
|
---|---|
返回: | An Image object. |
Creates a new image by interpolating between two input images, using a constant alpha.:
out = image1 * (1.0 - alpha) + image2 * alpha
参数: |
|
---|---|
返回: | An Image object. |
Create composite image by blending images using a transparency mask.
参数: |
|
---|
Applies the function (which should take one argument) to each pixel in the given image. If the image has more than one band, the same function is applied to each band. Note that the function is evaluated once for each possible pixel value, so you cannot use random components or other generators.
参数: |
|
---|---|
返回: | An Image object. |
Creates a new image with the given mode and size.
参数: |
|
---|---|
返回: | An Image object. |
Creates an image memory from an object exporting the array interface (using the buffer protocol).
If obj is not contiguous, then the tobytes method is called and frombuffer() is used.
参数: |
|
---|---|
返回: | An image memory. |
1.1.6 新版功能.
Creates a copy of an image memory from pixel data in a buffer.
In its simplest form, this function takes three arguments (mode, size, and unpacked pixel data).
You can also use any pixel decoder supported by PIL. For more information on available decoders, see the section Writing Your Own File Decoder.
Note that this function decodes pixel data only, not entire images. If you have an entire image in a string, wrap it in a BytesIO object, and use open() to load it.
参数: |
|
---|---|
返回: | An Image object. |
Creates an image memory referencing pixel data in a byte buffer.
This function is similar to frombytes(), but uses data in the byte buffer, where possible. This means that changes to the original buffer object are reflected in this image). Not all modes can share memory; supported modes include “L”, “RGBX”, “RGBA”, and “CMYK”.
Note that this function decodes pixel data only, not entire images. If you have an entire image file in a string, wrap it in a BytesIO object, and use open() to load it.
In the current version, the default parameters used for the “raw” decoder differs from that used for fromstring(). This is a bug, and will probably be fixed in a future release. The current release issues a warning if you do this; to disable the warning, you should provide the full set of parameters. See below for details.
参数: |
|
---|---|
返回: | An Image object. |
1.1.4 新版功能.
注解
These functions are for use by plugin authors. Application authors can ignore them.
Register an image file plugin. This function should not be used in application code.
参数: |
|
---|
Registers an image MIME type. This function should not be used in application code.
参数: |
|
---|
This class represents an image object. To create Image objects, use the appropriate factory functions. There’s hardly ever any reason to call the Image constructor directly.
An instance of the Image class has the following methods. Unless otherwise stated, all methods return a new instance of the Image class, holding the resulting image.
Returns a converted copy of this image. For the “P” mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.
The current version supports all possible conversions between “L”, “RGB” and “CMYK.” The matrix argument only supports “L” and “RGB”.
When translating a color image to black and white (mode “L”), the library uses the ITU-R 601-2 luma transform:
L = R * 299/1000 + G * 587/1000 + B * 114/1000
The default method of converting a greyscale (“L”) or “RGB” image into a bilevel (mode “1”) image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is NONE, all non-zero values are set to 255 (white). To use other thresholds, use the point() method.
参数: |
|
---|---|
返回类型: | |
返回: | An Image object. |
The following example converts an RGB image (linearly calibrated according to ITU-R 709, using the D65 luminant) to the CIE XYZ color space:
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)
Copies this image. Use this method if you wish to paste things into an image, but still retain the original.
返回类型: | Image |
---|---|
返回: | An Image object. |
Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.
This is a lazy operation. Changes to the source image may or may not be reflected in the cropped image. To break the connection, call the load() method on the cropped copy.
参数: | box – The crop rectangle, as a (left, upper, right, lower)-tuple. |
---|---|
返回类型: | Image |
返回: | An Image object. |
NYI
Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it, or to extract a 128x192 version from a PCD file.
Note that this method modifies the Image object in place. If the image has already been loaded, this method has no effect.
参数: |
|
---|
Filters this image using the given filter. For a list of available filters, see the ImageFilter module.
参数: | filter – Filter kernel. |
---|---|
返回: | An Image object. |
Returns a tuple containing the name of each band in this image. For example, getbands on an RGB image returns (“R”, “G”, “B”).
返回: | A tuple containing band names. |
---|---|
返回类型: | tuple |
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. |
---|
Returns a list of colors used in this image.
参数: | maxcolors – Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. |
---|---|
返回: | An unsorted list of (count, pixel) values. |
Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.
Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).
参数: | band – What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the “R” band from an “RGB” image). |
---|---|
返回: | A sequence-like object. |
Gets the the minimum and maximum pixel values for each band in the image.
返回: | For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. |
---|
Returns the pixel value at a given position.
参数: | xy – The coordinate, given as (x, y). |
---|---|
返回: | The pixel value. If the image is a multi-layer image, this method returns a tuple. |
Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an “RGB” image contains 768 values).
A bilevel image (mode “1”) is treated as a greyscale (“L”) image by this method.
If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode “1”) or a greyscale image (“L”).
参数: | mask – An optional mask. |
---|---|
返回: | A list containing pixel counts. |
2.0 版后已移除.
注解
New code should use PIL.ImageChops.offset().
Returns a copy of the image where the data has been offset by the given distances. Data wraps around the edges. If yoffset is omitted, it is assumed to be equal to xoffset.
参数: |
|
---|---|
返回: | An Image object. |
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).
Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module.
If a mask is given, this method 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.
参数: |
|
---|
Maps this image through a lookup table or function.
参数: |
|
---|---|
返回: | An Image object. |
Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it’s converted to “LA” or “RGBA”. The new layer must be either “L” or “1”.
参数: | alpha – The new alpha layer. This can either be an “L” or “1” image having the same size as this image, or an integer or other color value. |
---|
Copies pixel data to this image. This method copies data from a sequence object into the image, starting at the upper left corner (0, 0), and continuing until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: pixel = value*scale + offset.
参数: |
|
---|
Attaches a palette to this image. The image must be a “P” or “L” image, and the palette sequence must 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.
参数: | data – A palette sequence (either a list or a string). |
---|
Modifies the pixel at the given position. The color 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.
See:
参数: |
|
---|
Returns a resized copy of this image.
参数: |
|
---|---|
返回: | An Image object. |
Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre.
参数: |
|
---|---|
返回: | An Image object. |
Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible.
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.
参数: |
|
---|---|
返回: | None |
引发: |
|
Seeks to the given frame in this 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.
See tell().
参数: | frame – Frame number, starting at 0. |
---|---|
引发 EOFError: | If the call attempts to seek beyond the end of the sequence. |
Displays this image. This method is mainly intended for debugging purposes.
On Unix platforms, this method saves the image to a temporary PPM file, and calls the xv utility.
On Windows, it saves the image to a temporary BMP file, and uses the standard BMP display utility to show it (usually Paint).
参数: |
|
---|
Split this image into individual bands. This method 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).
返回: | A tuple containing bands. |
---|
Returns the current frame number. See seek().
返回: | Frame number, starting with 0. |
---|
Make this image into a thumbnail. This method 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.
Note that the bilinear and bicubic filters in the current version of PIL are not well-suited for thumbnail generation. You should use PIL.Image.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.
参数: |
|
---|---|
返回: | None |
Returns the image converted to an X11 bitmap.
注解
This method only works for mode “1” images.
参数: | name – The name prefix to use for the bitmap variables. |
---|---|
返回: | A string containing an X11 bitmap. |
引发 ValueError: | If the mode is not “1” |
Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform.
参数: |
|
---|---|
返回: | An Image object. |
Transpose image (flip or rotate in 90 degree steps)
参数: | method – One of PIL.Image.FLIP_LEFT_RIGHT, PIL.Image.FLIP_TOP_BOTTOM, PIL.Image.ROTATE_90, PIL.Image.ROTATE_180, or PIL.Image.ROTATE_270. |
---|---|
返回: | Returns a flipped or rotated copy of this image. |
Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file.
Allocates storage for the image and loads the pixel data. In normal cases, you don’t need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. This method will close the file associated with the image.
返回: | An image access object. |
---|
Instances of the Image class have the following attributes:
The file format of the source file. For images created by the library itself (via a factory function, or by running a method on an existing image), this attribute is set to None.
Type : | string or None |
---|
Image mode. This is a string specifying the pixel format used by the image. Typical values are “1”, “L”, “RGB”, or “CMYK.” See 概念 for a full list.
Type : | string |
---|
Image size, in pixels. The size is given as a 2-tuple (width, height).
Type : | (width, height) |
---|
Colour palette table, if any. If mode is “P”, this should be an instance of the ImagePalette class. Otherwise, it should be set to None.
Type : | ImagePalette or None |
---|
A dictionary holding data associated with the image. This dictionary is used by file handlers to pass on various non-image information read from the file. See documentation for the various file handlers for details.
Most methods ignore the dictionary when returning new images; since the keys are not standardized, it’s not possible for a method to know if the operation affects the dictionary. If you need the information later on, keep a reference to the info dictionary returned from the open method.
Type : | dict |
---|