鱼C论坛

 找回密码
 立即注册
查看: 5135|回复: 28

[技术交流] python图像处理库pillow使用说明

[复制链接]
发表于 2016-11-8 11:58:16 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
原文地址:http://pillow.readthedocs.io/en/3.1.x/reference/Image.html

Image Module
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.

Examples
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).

Open, rotate, and display an image (using the default viewer)
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.

Create thumbnails
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)
    im.save(file + ".thumbnail", "JPEG")
Functions
PIL.Image.open(fp, mode='r')
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().

Parameters:       
fp – A filename (string), pathlib.Path object or a file object. The file object must implement read(), seek(), and tell() methods, and be opened in binary mode.
mode – The mode. If given, this argument must be “r”.
Returns:       
An Image object.

Raises:       
IOError – If the file cannot be found, or the image cannot be opened and identified.

Warning

To protect against potential DOS attacks caused by “decompression bombs” (i.e. malicious files which decompress into a huge amount of data and are designed to crash or cause disruption by using up a lot of memory), Pillow will issue a DecompressionBombWarning if the image is over a certain limit. If desired, the warning can be turned into an error with warnings.simplefilter('error', Image.DecompressionBombWarning) or suppressed entirely with warnings.simplefilter('ignore', Image.DecompressionBombWarning). See also the logging documentation to have warnings output to the logging facility instead of stderr.

Image processing
PIL.Image.alpha_composite(im1, im2)
Alpha composite im2 over im1.

Parameters:       
im1 – The first image.
im2 – The second image. Must have the same mode and size as the first image.
Returns:       
An Image object.

PIL.Image.blend(im1, im2, alpha)
Creates a new image by interpolating between two input images, using a constant alpha.:

out = image1 * (1.0 - alpha) + image2 * alpha
Parameters:       
im1 – The first image.
im2 – The second image. Must have the same mode and size as the first image.
alpha – The interpolation alpha factor. If alpha is 0.0, a copy of the first image is returned. If alpha is 1.0, a copy of the second image is returned. There are no restrictions on the alpha value. If necessary, the result is clipped to fit into the allowed output range.
Returns:       
An Image object.

PIL.Image.composite(image1, image2, mask)
Create composite image by blending images using a transparency mask.

Parameters:       
image1 – The first image.
image2 – The second image. Must have the same mode and size as the first image.
mask – A mask image. This image can have mode “1”, “L”, or “RGBA”, and must have the same size as the other two images.
PIL.Image.eval(image, *args)
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.

Parameters:       
image – The input image.
function – A function object, taking one integer argument.
Returns:       
An Image object.

PIL.Image.merge(mode, bands)
Merge a set of single band images into a new multiband image.

Parameters:       
mode – The mode to use for the output image. See: Modes.
bands – A sequence containing one single-band image for each band in the output image. All bands must have the same size.
Returns:       
An Image object.

Constructing images
PIL.Image.new(mode, size, color=0)
Creates a new image with the given mode and size.

Parameters:       
mode – The mode to use for the new image. See: Modes.
size – A 2-tuple, containing (width, height) in pixels.
color – What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes (one value per band). When creating RGB images, you can also use color strings as supported by the ImageColor module. If the color is None, the image is not initialised.
Returns:       
An Image object.

PIL.Image.fromarray(obj, mode=None)
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.

Parameters:       
obj – Object with array interface
mode – Mode to use (will be determined from type if None) See: Modes.
Returns:       
An image object.

New in version 1.1.6.

PIL.Image.frombytes(mode, size, data, decoder_name='raw', *args)
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.

Parameters:       
mode – The image mode. See: Modes.
size – The image size.
data – A byte buffer containing raw data for the given mode.
decoder_name – What decoder to use.
args – Additional parameters for the given decoder.
Returns:       
An Image object.

PIL.Image.fromstring(*args, **kw)
PIL.Image.frombuffer(mode, size, data, decoder_name='raw', *args)
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.

Parameters:       
mode – The image mode. See: Modes.
size – The image size.
data – A bytes or other buffer object containing raw data for the given mode.
decoder_name – What decoder to use.
args –
Additional parameters for the given decoder. For the default encoder (“raw”), it’s recommended that you provide the full set of parameters:

frombuffer(mode, size, data, "raw", mode, 0, 1)
Returns:       
An Image object.

New in version 1.1.4.

Registering plugins
Note

These functions are for use by plugin authors. Application authors can ignore them.
PIL.Image.register_open(id, factory, accept=None)
Register an image file plugin. This function should not be used in application code.

Parameters:       
id – An image format identifier.
factory – An image file factory method.
accept – An optional function that can be used to quickly reject images having another format.
PIL.Image.register_mime(id, mimetype)
Registers an image MIME type. This function should not be used in application code.

Parameters:       
id – An image format identifier.
mimetype – The image MIME type for this format.
PIL.Image.register_save(id, driver)
Registers an image save function. This function should not be used in application code.

Parameters:       
id – An image format identifier.
driver – A function to save images in this format.
PIL.Image.register_extension(id, extension)
Registers an image extension. This function should not be used in application code.

Parameters:       
id – An image format identifier.
extension – An extension used for this format.
The Image Class
class PIL.Image.Image
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.

open()
new()
frombytes()
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.

Image.convert(mode=None, matrix=None, dither=None, palette=0, colors=256)
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.

Parameters:       
mode – The requested mode. See: Modes.
matrix – An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values.
dither – Dithering method, used when converting from mode “RGB” to “P” or from “RGB” or “L” to “1”. Available methods are NONE or FLOYDSTEINBERG (default).
palette – Palette to use when converting from mode “RGB” to “P”. Available palettes are WEB or ADAPTIVE.
colors – Number of colors to use for the ADAPTIVE palette. Defaults to 256.
Return type:       
Image

Returns:       
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)
Image.copy()
Copies this image. Use this method if you wish to paste things into an image, but still retain the original.

Return type:        Image
Returns:        An Image object.
Image.crop(box=None)
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.

Parameters:        box – The crop rectangle, as a (left, upper, right, lower)-tuple.
Return type:        Image
Returns:        An Image object.
Image.draft(mode, size)
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.

Parameters:       
mode – The requested mode.
size – The requested size.
Image.filter(filter)
Filters this image using the given filter. For a list of available filters, see the ImageFilter module.

Parameters:        filter – Filter kernel.
Returns:        An Image object.
Image.getbands()
Returns a tuple containing the name of each band in this image. For example, getbands on an RGB image returns (“R”, “G”, “B”).

Returns:        A tuple containing band names.
Return type:        tuple
Image.getbbox()
Calculates the bounding box of the non-zero regions in the image.

Returns:        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.
Image.getcolors(maxcolors=256)
Returns a list of colors used in this image.

Parameters:        maxcolors – Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors.
Returns:        An unsorted list of (count, pixel) values.
Image.getdata(band=None)
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()).

Parameters:        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).
Returns:        A sequence-like object.
Image.getextrema()
Gets the the minimum and maximum pixel values for each band in the image.

Returns:        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.
Image.getpalette()
Returns the image palette as a list.

Returns:        A list of color values [r, g, b, ...], or None if the image has no palette.
Image.getpixel(xy)
Returns the pixel value at a given position.

Parameters:        xy – The coordinate, given as (x, y).
Returns:        The pixel value. If the image is a multi-layer image, this method returns a tuple.
Image.histogram(mask=None, extrema=None)
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”).

Parameters:        mask – An optional mask.
Returns:        A list containing pixel counts.
Image.offset(xoffset, yoffset=None)
Image.paste(im, box=None, mask=None)
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 will mix the two images together, including their alpha channels if they have them.

See alpha_composite() if you want to combine images with respect to their alpha channels.

Parameters:       
im – Source image or pixel value (integer or tuple).
box –
An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it’s treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner.

If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image.

mask – An optional mask image.
Image.point(lut, mode=None)
Maps this image through a lookup table or function.

Parameters:       
lut – A lookup table, containing 256 (or 65336 if self.mode==”I” and mode == “L”) values per band in the image. A function can be 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.
mode – Output mode (default is same as input). In the current version, this can only be used if the source image has mode “L” or “P”, and the output has mode “1” or the source image mode is “I” and the output mode is “L”.
Returns:       
An Image object.

Image.putalpha(alpha)
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”.

Parameters:        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.
Image.putdata(data, scale=1.0, offset=0.0)
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.

Parameters:       
data – A sequence object.
scale – An optional scale value. The default is 1.0.
offset – An optional offset value. The default is 0.0.
Image.putpalette(data, rawmode='RGB')
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.

Parameters:        data – A palette sequence (either a list or a string).
Image.putpixel(xy, value)
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:

paste()
putdata()
ImageDraw
Parameters:       
xy – The pixel coordinate, given as (x, y).
value – The pixel value.
Image.quantize(colors=256, method=None, kmeans=0, palette=None)
Convert the image to ‘P’ mode with the specified number of colors.

Parameters:       
colors – The desired number of colors, <= 256
method – 0 = median cut 1 = maximum coverage 2 = fast octree
kmeans – Integer
palette – Quantize to the PIL.ImagingPalette palette.
Returns:       
A new image

Image.resize(size, resample=0)
Returns a resized copy of this image.

Parameters:       
size – The requested size in pixels, as a 2-tuple: (width, height).
resample – An optional resampling filter. This can be one of PIL.Image.NEAREST (use nearest neighbour), PIL.Image.BILINEAR (linear interpolation), PIL.Image.BICUBIC (cubic spline interpolation), or PIL.Image.LANCZOS (a high-quality downsampling filter). If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST.
Returns:       
An Image object.

Image.rotate(angle, resample=0, expand=0)
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.

Parameters:       
angle – In degrees counter clockwise.
resample – An optional resampling filter. This can be one of PIL.Image.NEAREST (use nearest neighbour), PIL.Image.BILINEAR (linear interpolation in a 2x2 environment), or PIL.Image.BICUBIC (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST.
expand – Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image.
Returns:       
An Image object.

Image.save(fp, format=None, **params)
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 in the image format documentation for each writer.

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.

Parameters:       
fp – A filename (string), pathlib.Path object or file object.
format – Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used.
options – Extra parameters to the image writer.
Returns:       
None

Raises:       
KeyError – If the output format could not be determined from the file name. Use the format option to solve this.
IOError – If the file could not be written. The file may have been created, and may contain partial data.
Image.seek(frame)
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().

Parameters:        frame – Frame number, starting at 0.
Raises:        EOFError – If the call attempts to seek beyond the end of the sequence.
Image.show(title=None, command=None)
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).

Parameters:       
title – Optional title to use for the image window, where possible.
command – command used to show the image
Image.split()
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).

Returns:        A tuple containing bands.
Image.tell()
Returns the current frame number. See seek().

Returns:        Frame number, starting with 0.
Image.thumbnail(size, resample=3)
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 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.

Parameters:       
size – Requested size.
resample – Optional resampling filter. This can be one of PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC, or PIL.Image.LANCZOS. If omitted, it defaults to PIL.Image.BICUBIC. (was PIL.Image.NEAREST prior to version 2.5.0)
Returns:       
None

Image.tobitmap(name='image')
Returns the image converted to an X11 bitmap.

Note

This method only works for mode “1” images.

Parameters:        name – The name prefix to use for the bitmap variables.
Returns:        A string containing an X11 bitmap.
Raises:        ValueError – If the mode is not “1”
Image.tobytes(encoder_name='raw', *args)
Return image as a bytes object.

Warning

This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use save(), with a BytesIO parameter for in-memory data.

Parameters:       
encoder_name – What encoder to use. The default is to use the standard “raw” encoder.
args – Extra arguments to the encoder.
Return type:       
A bytes object.

Image.tostring(*args, **kw)
Image.transform(size, method, data=None, resample=0, fill=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.

Parameters:       
size – The output size.
method – The transformation method. This is one of PIL.Image.EXTENT (cut out a rectangular subregion), PIL.Image.AFFINE (affine transform), PIL.Image.PERSPECTIVE (perspective transform), PIL.Image.QUAD (map a quadrilateral to a rectangle), or PIL.Image.MESH (map a number of source quadrilaterals in one operation).
data – Extra data to the transformation method.
resample – Optional resampling filter. It can be one of PIL.Image.NEAREST (use nearest neighbour), PIL.Image.BILINEAR (linear interpolation in a 2x2 environment), or PIL.Image.BICUBIC (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode “1” or “P”, it is set to PIL.Image.NEAREST.
Returns:       
An Image object.

Image.transpose(method)
Transpose image (flip or rotate in 90 degree steps)

Parameters:        method – One of PIL.Image.FLIP_LEFT_RIGHT, PIL.Image.FLIP_TOP_BOTTOM, PIL.Image.ROTATE_90, PIL.Image.ROTATE_180, PIL.Image.ROTATE_270 or PIL.Image.TRANSPOSE.
Returns:        Returns a flipped or rotated copy of this image.
Image.verify()
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.

Image.fromstring(*args, **kw)
Image.load()
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.

Returns:        An image access object.
Return type:        PixelAccess Class or PIL.PyAccess
Image.close()
Closes the file pointer, if possible.

This operation will destroy the image core and release its memory. The image data will be unusable afterward.

This function is only required to close images that have not had their file read and closed by the load() method.

Attributes
Instances of the Image class have the following attributes:

PIL.Image.format
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
PIL.Image.mode
Image mode. This is a string specifying the pixel format used by the image. Typical values are “1”, “L”, “RGB”, or “CMYK.” See Modes for a full list.

Type:        string
PIL.Image.size
Image size, in pixels. The size is given as a 2-tuple (width, height).

Type:        (width, height)
PIL.Image.width
Image width, in pixels.

Type:        int
PIL.Image.height
Image height, in pixels.

Type:        int
PIL.Image.palette
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
PIL.Image.info
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.

Unless noted elsewhere, this dictionary does not affect saving files.

Type:        dict
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-3-28 19:54:49 | 显示全部楼层
阿巴阿巴,看不懂
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-11-19 19:35:12 | 显示全部楼层
这是啥?高大上啊~
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 16:23:27 | 显示全部楼层
Plugin reference
BmpImagePlugin Module
class PIL.BmpImagePlugin.BmpImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

Image plugin for the Windows Bitmap format (BMP)

BITFIELDS = 3
COMPRESSIONS = {'RLE4': 2, 'JPEG': 4, 'BITFIELDS': 3, 'RAW': 0, 'RLE8': 1, 'PNG': 5}
JPEG = 4
PNG = 5
RAW = 0
RLE4 = 2
RLE8 = 1
format = 'BMP'
format_description = 'Windows Bitmap'
class PIL.BmpImagePlugin.DibImageFile(fp=None, filename=None)
Bases: PIL.BmpImagePlugin.BmpImageFile

format = 'DIB'
format_description = 'Windows Bitmap'
BufrStubImagePlugin Module
class PIL.BufrStubImagePlugin.BufrStubImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.StubImageFile

format = 'BUFR'
format_description = 'BUFR'
PIL.BufrStubImagePlugin.register_handler(handler)
CurImagePlugin Module
class PIL.CurImagePlugin.CurImageFile(fp=None, filename=None)
Bases: PIL.BmpImagePlugin.BmpImageFile

format = 'CUR'
format_description = 'Windows Cursor'
DcxImagePlugin Module
class PIL.DcxImagePlugin.DcxImageFile(fp=None, filename=None)
Bases: PIL.PcxImagePlugin.PcxImageFile

format = 'DCX'
format_description = 'Intel DCX'
is_animated
n_frames
seek(frame)
tell()
EpsImagePlugin Module
class PIL.EpsImagePlugin.EpsImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

EPS File Parser for the Python Imaging Library

format = 'EPS'
format_description = 'Encapsulated Postscript'
load(scale=1)
load_seek(*args, **kwargs)
mode_map = {1: 'L', 2: 'LAB', 3: 'RGB'}
PIL.EpsImagePlugin.Ghostscript(tile, size, fp, scale=1)
Render an image using Ghostscript

class PIL.EpsImagePlugin.PSFile(fp)
Bases: object

Wrapper for bytesio object that treats either CR or LF as end of line.

readline()
seek(offset, whence=0)
PIL.EpsImagePlugin.has_ghostscript()
FitsStubImagePlugin Module
class PIL.FitsStubImagePlugin.FITSStubImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.StubImageFile

format = 'FITS'
format_description = 'FITS'
PIL.FitsStubImagePlugin.register_handler(handler)
FliImagePlugin Module
class PIL.FliImagePlugin.FliImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'FLI'
format_description = 'Autodesk FLI/FLC Animation'
is_animated
n_frames
seek(frame)
tell()
FpxImagePlugin Module
class PIL.FpxImagePlugin.FpxImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'FPX'
format_description = 'FlashPix'
load()
GbrImagePlugin Module
class PIL.GbrImagePlugin.GbrImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'GBR'
format_description = 'GIMP brush file'
load()
GifImagePlugin Module
class PIL.GifImagePlugin.GifImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

data()
format = 'GIF'
format_description = 'Compuserve GIF'
global_palette = None
is_animated
load_end()
n_frames
seek(frame)
tell()
PIL.GifImagePlugin.get_interlace(im)
PIL.GifImagePlugin.getdata(im, offset=(0, 0), **params)
Return a list of strings representing this image. The first string is a local image header, the rest contains encoded image data.

PIL.GifImagePlugin.getheader(im, palette=None, info=None)
Return a list of strings representing a GIF header

GribStubImagePlugin Module
class PIL.GribStubImagePlugin.GribStubImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.StubImageFile

format = 'GRIB'
format_description = 'GRIB'
PIL.GribStubImagePlugin.register_handler(handler)
Hdf5StubImagePlugin Module
class PIL.Hdf5StubImagePlugin.HDF5StubImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.StubImageFile

format = 'HDF5'
format_description = 'HDF5'
PIL.Hdf5StubImagePlugin.register_handler(handler)
IcnsImagePlugin Module
class PIL.IcnsImagePlugin.IcnsFile(fobj)
Bases: object

SIZES = {(256, 256, 1): [('ic08', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (128, 128, 2): [('ic13', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (64, 64, 1): [('icp6', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (128, 128, 1): [('ic07', <function read_png_or_jpeg2000 at 0x7f9f3a770758>), ('it32', <function read_32t at 0x7f9f3a7705f0>), ('t8mk', <function read_mk at 0x7f9f3a7706e0>)], (32, 32, 1): [('icp5', <function read_png_or_jpeg2000 at 0x7f9f3a770758>), ('il32', <function read_32 at 0x7f9f3a770668>), ('l8mk', <function read_mk at 0x7f9f3a7706e0>)], (16, 16, 2): [('ic11', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (512, 512, 2): [('ic10', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (512, 512, 1): [('ic09', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (48, 48, 1): [('ih32', <function read_32 at 0x7f9f3a770668>), ('h8mk', <function read_mk at 0x7f9f3a7706e0>)], (256, 256, 2): [('ic14', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)], (16, 16, 1): [('icp4', <function read_png_or_jpeg2000 at 0x7f9f3a770758>), ('is32', <function read_32 at 0x7f9f3a770668>), ('s8mk', <function read_mk at 0x7f9f3a7706e0>)], (32, 32, 2): [('ic12', <function read_png_or_jpeg2000 at 0x7f9f3a770758>)]}
bestsize()
dataforsize(size)
Get an icon resource as {channel: array}. Note that the arrays are bottom-up like windows bitmaps and will likely need to be flipped or transposed in some way.

getimage(size=None)
itersizes()
class PIL.IcnsImagePlugin.IcnsImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

PIL image support for Mac OS .icns files. Chooses the best resolution, but will possibly load a different size image if you mutate the size attribute before calling ‘load’.

The info dictionary has a key ‘sizes’ that is a list of sizes that the icns file has.

format = 'ICNS'
format_description = 'Mac OS icns resource'
load()
PIL.IcnsImagePlugin.nextheader(fobj)
PIL.IcnsImagePlugin.read_32(fobj, start_length, size)
Read a 32bit RGB icon resource. Seems to be either uncompressed or an RLE packbits-like scheme.

PIL.IcnsImagePlugin.read_32t(fobj, start_length, size)
PIL.IcnsImagePlugin.read_mk(fobj, start_length, size)
PIL.IcnsImagePlugin.read_png_or_jpeg2000(fobj, start_length, size)
IcoImagePlugin Module
class PIL.IcoImagePlugin.IcoFile(buf)
Bases: object

frame(idx)
Get an image from frame idx

getimage(size, bpp=False)
Get an image from the icon

sizes()
Get a list of all available icon sizes and color depths.

class PIL.IcoImagePlugin.IcoImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

PIL read-only image support for Microsoft Windows .ico files.

By default the largest resolution image in the file will be loaded. This can be changed by altering the ‘size’ attribute before calling ‘load’.

The info dictionary has a key ‘sizes’ that is a list of the sizes available in the icon file.

Handles classic, XP and Vista icon formats.

This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis <casadebender@gmail.com>. https://code.google.com/p/casadebender/wiki/Win32IconImagePlugin

format = 'ICO'
format_description = 'Windows Icon'
load()
load_seek()
ImImagePlugin Module
class PIL.ImImagePlugin.ImImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'IM'
format_description = 'IFUNC Image Memory'
is_animated
n_frames
seek(frame)
tell()
PIL.ImImagePlugin.number(s)
ImtImagePlugin Module
class PIL.ImtImagePlugin.ImtImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'IMT'
format_description = 'IM Tools'
IptcImagePlugin Module
class PIL.IptcImagePlugin.IptcImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

field()
format = 'IPTC'
format_description = 'IPTC/NAA'
getint(key)
load()
PIL.IptcImagePlugin.dump(c)
PIL.IptcImagePlugin.getiptcinfo(im)
PIL.IptcImagePlugin.i(c)
JpegImagePlugin Module
PIL.JpegImagePlugin.APP(self, marker)
PIL.JpegImagePlugin.COM(self, marker)
PIL.JpegImagePlugin.DQT(self, marker)
class PIL.JpegImagePlugin.JpegImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

draft(mode, size)
format = 'JPEG'
format_description = 'JPEG (ISO 10918)'
load_djpeg()
PIL.JpegImagePlugin.SOF(self, marker)
PIL.JpegImagePlugin.Skip(self, marker)
PIL.JpegImagePlugin.convert_dict_qtables(qtables)
PIL.JpegImagePlugin.get_sampling(im)
PIL.JpegImagePlugin.jpeg_factory(fp=None, filename=None)
Jpeg2KImagePlugin Module
class PIL.Jpeg2KImagePlugin.Jpeg2KImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'JPEG2000'
format_description = 'JPEG 2000 (ISO 15444)'
load()
McIdasImagePlugin Module
class PIL.McIdasImagePlugin.McIdasImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'MCIDAS'
format_description = 'McIdas area file'
MicImagePlugin Module
class PIL.MicImagePlugin.MicImageFile(fp=None, filename=None)
Bases: PIL.TiffImagePlugin.TiffImageFile

format = 'MIC'
format_description = 'Microsoft Image Composer'
is_animated
n_frames
seek(frame)
tell()
MpegImagePlugin Module
class PIL.MpegImagePlugin.BitStream(fp)
Bases: object

next()
peek(bits)
read(bits)
skip(bits)
class PIL.MpegImagePlugin.MpegImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'MPEG'
format_description = 'MPEG'
MspImagePlugin Module
class PIL.MspImagePlugin.MspImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'MSP'
format_description = 'Windows Paint'
PalmImagePlugin Module
PIL.PalmImagePlugin.build_prototype_image()
PcdImagePlugin Module
class PIL.PcdImagePlugin.PcdImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'PCD'
format_description = 'Kodak PhotoCD'
PcxImagePlugin Module
class PIL.PcxImagePlugin.PcxImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'PCX'
format_description = 'Paintbrush'
PdfImagePlugin Module
PixarImagePlugin Module
class PIL.PixarImagePlugin.PixarImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'PIXAR'
format_description = 'PIXAR raster image'
PngImagePlugin Module
PIL.PngImagePlugin.getchunks(im, **params)
Return a list of PNG chunks representing this image.

PIL.PngImagePlugin.is_cid()
match(string[, pos[, endpos]]) –> match object or None. Matches zero or more characters at the beginning of the string

PIL.PngImagePlugin.putchunk(fp, cid, *data)
Write a PNG chunk (including CRC field)

class PIL.PngImagePlugin.ChunkStream(fp)
Bases: object

call(cid, pos, length)
Call the appropriate chunk handler

close()
crc(cid, data)
Read and verify checksum

crc_skip(cid, data)
Read checksum. Used if the C module is not present

push(cid, pos, length)
read()
Fetch a new chunk. Returns header information.

verify(endchunk='IEND')
class PIL.PngImagePlugin.PngImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'PNG'
format_description = 'Portable network graphics'
load_end()
internal: finished reading image data

load_prepare()
internal: prepare to read PNG file

load_read(read_bytes)
internal: read more image data

verify()
Verify PNG file

class PIL.PngImagePlugin.PngStream(fp)
Bases: PIL.PngImagePlugin.ChunkStream

check_text_memory(chunklen)
chunk_IDAT(pos, length)
chunk_IEND(pos, length)
chunk_IHDR(pos, length)
chunk_PLTE(pos, length)
chunk_gAMA(pos, length)
chunk_iCCP(pos, length)
chunk_iTXt(pos, length)
chunk_pHYs(pos, length)
chunk_tEXt(pos, length)
chunk_tRNS(pos, length)
chunk_zTXt(pos, length)
PpmImagePlugin Module
class PIL.PpmImagePlugin.PpmImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'PPM'
format_description = 'Pbmplus image'
PsdImagePlugin Module
class PIL.PsdImagePlugin.PsdImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'PSD'
format_description = 'Adobe Photoshop'
is_animated
load_prepare()
n_frames
seek(layer)
tell()
SgiImagePlugin Module
class PIL.SgiImagePlugin.SgiImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'SGI'
format_description = 'SGI Image File Format'
SpiderImagePlugin Module
class PIL.SpiderImagePlugin.SpiderImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

convert2byte(depth=255)
format = 'SPIDER'
format_description = 'Spider 2D image'
is_animated
n_frames
seek(frame)
tell()
tkPhotoImage()
PIL.SpiderImagePlugin.isInt(f)
PIL.SpiderImagePlugin.isSpiderHeader(t)
PIL.SpiderImagePlugin.isSpiderImage(filename)
PIL.SpiderImagePlugin.loadImageSeries(filelist=None)
create a list of Image.images for use in montage

PIL.SpiderImagePlugin.makeSpiderHeader(im)
SunImagePlugin Module
class PIL.SunImagePlugin.SunImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'SUN'
format_description = 'Sun Raster File'
TgaImagePlugin Module
class PIL.TgaImagePlugin.TgaImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'TGA'
format_description = 'Targa'
TiffImagePlugin Module
class PIL.TiffImagePlugin.IFDRational(value, denominator=1)
Bases: numbers.Rational

Implements a rational class where 0/0 is a legal value to match the in the wild use of exif rationals.

e.g., DigitalZoomRatio - 0.00/0.00 indicates that no digital zoom was used

denominator
limit_rational(max_denominator)
Parameters:        max_denominator – Integer, the maximum denominator value
Returns:        Tuple of (numerator, denominator)
numerator
PIL.TiffImagePlugin.ImageFileDirectory
alias of ImageFileDirectory_v1

class PIL.TiffImagePlugin.ImageFileDirectory_v1(*args, **kwargs)
Bases: PIL.TiffImagePlugin.ImageFileDirectory_v2

This class represents the legacy interface to a TIFF tag directory.

Exposes a dictionary interface of the tags in the directory:

ifd = ImageFileDirectory_v1()
ifd[key] = 'Some Data'
ifd.tagtype[key] = 2
print ifd[key]
('Some Data',)
Also contains a dictionary of tag types as read from the tiff image file, ~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype.

Values are returned as a tuple.

Deprecated since version 3.0.0.

classmethod from_v2(original)
Returns an ImageFileDirectory_v1 instance with the same data as is contained in the original ImageFileDirectory_v2 instance.

Returns:        ImageFileDirectory_v1
tagdata
tags
to_v2()
Returns an ImageFileDirectory_v2 instance with the same data as is contained in the original ImageFileDirectory_v1 instance.

Returns:        ImageFileDirectory_v2
class PIL.TiffImagePlugin.ImageFileDirectory_v2(ifh='II*x00x00x00x00x00', prefix=None)
Bases: _abcoll.MutableMapping

This class represents a TIFF tag directory. To speed things up, we don’t decode tags unless they’re asked for.

Exposes a dictionary interface of the tags in the directory:

ifd = ImageFileDirectory_v2()
ifd[key] = 'Some Data'
ifd.tagtype[key] = 2
print(ifd[key])
'Some Data'
Individual values are returned as the strings or numbers, sequences are returned as tuples of the values.

The tiff metadata type of each item is stored in a dictionary of tag types in ~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype. The types are read from a tiff file, guessed from the type added, or added manually.

Data Structures:

self.tagtype = {}
Key: numerical tiff tag number
Value: integer corresponding to the data type from ~PIL.TiffTags.TYPES
New in version 3.0.0.

as_dict()
Return a dictionary of the image’s tags.

use dict(ifd) instead.

Deprecated since version 3.0.0.

has_key(tag)
legacy_api
load(fp)
load_byte(data, legacy_api=True)
load_double(data, legacy_api=True)
load_float(data, legacy_api=True)
load_long(data, legacy_api=True)
load_rational(data, legacy_api=True)
load_short(data, legacy_api=True)
load_signed_byte(data, legacy_api=True)
load_signed_long(data, legacy_api=True)
load_signed_rational(data, legacy_api=True)
load_signed_short(data, legacy_api=True)
load_string(data, legacy_api=True)
load_undefined(data, legacy_api=True)
named()
Returns:        dict of name|key: value
Returns the complete tag dictionary, with named tags where possible.

offset
prefix
reset()
save(fp)
write_byte(data)
write_double(*values)
write_float(*values)
write_long(*values)
write_rational(*values)
write_short(*values)
write_signed_byte(*values)
write_signed_long(*values)
write_signed_rational(*values)
write_signed_short(*values)
write_string(value)
write_undefined(value)
class PIL.TiffImagePlugin.TiffImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'TIFF'
format_description = 'Adobe TIFF'
is_animated
n_frames
seek(frame)
Select a given frame as current image

tell()
Return the current frame number

WebPImagePlugin Module
class PIL.WebPImagePlugin.WebPImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'WEBP'
format_description = 'WebP image'
WmfImagePlugin Module
class PIL.WmfImagePlugin.WmfStubImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.StubImageFile

format = 'WMF'
format_description = 'Windows Metafile'
PIL.WmfImagePlugin.register_handler(handler)
PIL.WmfImagePlugin.short(c, o=0)
XVThumbImagePlugin Module
class PIL.XVThumbImagePlugin.XVThumbImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'XVThumb'
format_description = 'XV thumbnail image'
XbmImagePlugin Module
class PIL.XbmImagePlugin.XbmImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'XBM'
format_description = 'X11 Bitmap'
XpmImagePlugin Module

class PIL.XpmImagePlugin.XpmImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'XPM'
format_description = 'X11 Pixel Map'
load_read(bytes)
Next  Previous
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 16:22:17 | 显示全部楼层
PIL Package (autodoc of remaining modules)
Reference for modules whose documentation has not yet been ported or written can be found here.

BdfFontFile Module
class PIL.BdfFontFile.BdfFontFile(fp)
Bases: PIL.FontFile.FontFile

PIL.BdfFontFile.bdf_char(f)
ContainerIO Module
class PIL.ContainerIO.ContainerIO(file, offset, length)
Bases: object

isatty()
read(n=0)
readline()
readlines()
seek(offset, mode=0)
tell()
FontFile Module
class PIL.FontFile.FontFile
Bases: object

bitmap = None
compile()
Create metrics and bitmap

save(filename)
Save font

PIL.FontFile.puti16(fp, values)
GdImageFile Module
class PIL.GdImageFile.GdImageFile(fp=None, filename=None)
Bases: PIL.ImageFile.ImageFile

format = 'GD'
format_description = 'GD uncompressed images'
PIL.GdImageFile.open(fp, mode='r')
GimpGradientFile Module
class PIL.GimpGradientFile.GimpGradientFile(fp)
Bases: PIL.GimpGradientFile.GradientFile

class PIL.GimpGradientFile.GradientFile
Bases: object

getpalette(entries=256)
gradient = None
PIL.GimpGradientFile.curved(middle, pos)
PIL.GimpGradientFile.linear(middle, pos)
PIL.GimpGradientFile.sine(middle, pos)
PIL.GimpGradientFile.sphere_decreasing(middle, pos)
PIL.GimpGradientFile.sphere_increasing(middle, pos)
GimpPaletteFile Module
class PIL.GimpPaletteFile.GimpPaletteFile(fp)
Bases: object

getpalette()
rawmode = 'RGB'
ImageDraw2 Module
class PIL.ImageDraw2.Brush(color, opacity=255)
Bases: object

class PIL.ImageDraw2.Draw(image, size=None, color=None)
Bases: object

arc(xy, start, end, *options)
chord(xy, start, end, *options)
ellipse(xy, *options)
flush()
line(xy, *options)
pieslice(xy, start, end, *options)
polygon(xy, *options)
rectangle(xy, *options)
render(op, xy, pen, brush=None)
settransform(offset)
symbol(xy, symbol, *options)
text(xy, text, font)
textsize(text, font)
class PIL.ImageDraw2.Font(color, file, size=12)
Bases: object

class PIL.ImageDraw2.Pen(color, width=1, opacity=255)
Bases: object

ImageShow Module
class PIL.ImageShow.DisplayViewer
Bases: PIL.ImageShow.UnixViewer

get_command_ex(file, **options)
class PIL.ImageShow.UnixViewer
Bases: PIL.ImageShow.Viewer

show_file(file, **options)
class PIL.ImageShow.Viewer
Bases: object

format = None
get_command(file, **options)
get_format(image)
save_image(image)
show(image, **options)
show_file(file, **options)
show_image(image, **options)
class PIL.ImageShow.XVViewer
Bases: PIL.ImageShow.UnixViewer

get_command_ex(file, title=None, **options)
PIL.ImageShow.register(viewer, order=1)
PIL.ImageShow.show(image, title=None, **options)
PIL.ImageShow.which(executable)
ImageTransform Module
class PIL.ImageTransform.AffineTransform(data)
Bases: PIL.ImageTransform.Transform

method = 0
class PIL.ImageTransform.ExtentTransform(data)
Bases: PIL.ImageTransform.Transform

method = 1
class PIL.ImageTransform.MeshTransform(data)
Bases: PIL.ImageTransform.Transform

method = 4
class PIL.ImageTransform.QuadTransform(data)
Bases: PIL.ImageTransform.Transform

method = 3
class PIL.ImageTransform.Transform(data)
Bases: PIL.Image.ImageTransformHandler

getdata()
transform(size, image, **options)
JpegPresets Module
JPEG quality settings equivalent to the Photoshop settings.

More presets can be added to the presets dict if needed.

Can be use when saving JPEG file.

To apply the preset, specify:

quality="preset_name"
To apply only the quantization table:

qtables="preset_name"
To apply only the subsampling setting:

subsampling="preset_name"
Example:

im.save("image_name.jpg", quality="web_high")
Subsampling
Subsampling is the practice of encoding images by implementing less resolution for chroma information than for luma information. (ref.: https://en.wikipedia.org/wiki/Chroma_subsampling)

Possible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2 and 4:1:1 (or 4:2:0?).

You can get the subsampling of a JPEG with the JpegImagePlugin.get_subsampling(im) function.

Quantization tables
They are values use by the DCT (Discrete cosine transform) to remove unnecessary information from the image (the lossy part of the compression). (ref.: https://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices, https://en.wikipedia.org/wiki/JPEG#Quantization)

You can get the quantization tables of a JPEG with:

im.quantization
This will return a dict with a number of arrays. You can pass this dict directly as the qtables argument when saving a JPEG.

The tables format between im.quantization and quantization in presets differ in 3 ways:

The base container of the preset is a list with sublists instead of dict. dict[0] -> list[0], dict[1] -> list[1], ...
Each table in a preset is a list instead of an array.
The zigzag order is remove in the preset (needed by libjpeg >= 6a).
You can convert the dict format to the preset format with the JpegImagePlugin.convert_dict_qtables(dict_qtables) function.

Libjpeg ref.: http://www.jpegcameras.com/libjpeg/libjpeg-3.html

PaletteFile Module
class PIL.PaletteFile.PaletteFile(fp)
Bases: object

getpalette()
rawmode = 'RGB'
PcfFontFile Module
class PIL.PcfFontFile.PcfFontFile(fp)
Bases: PIL.FontFile.FontFile

name = 'name'
PIL.PcfFontFile.sz(s, o)
PngImagePlugin.iTXt Class
class PIL.PngImagePlugin.iTXt
Bases: str

Subclass of string to allow iTXt chunks to look like strings while keeping their extra information

__new__(cls, text, lang, tkey)
Parameters:       
value – value for this key
lang – language code
tkey – UTF-8 version of the key name
PngImagePlugin.PngInfo Class
class PIL.PngImagePlugin.PngInfo
Bases: object

PNG chunk container (for use with save(pnginfo=))

add(cid, data)
Appends an arbitrary chunk. Use with caution.

Parameters:       
cid – a byte string, 4 bytes long.
data – a byte string of the encoded data
add_itxt(key, value, lang='', tkey='', zip=False)
Appends an iTXt chunk.

Parameters:       
key – latin-1 encodable text key name
value – value for this key
lang – language code
tkey – UTF-8 version of the key name
zip – compression flag
add_text(key, value, zip=0)
Appends a text chunk.

Parameters:       
key – latin-1 encodable text key name
value – value for this key, text or an PIL.PngImagePlugin.iTXt instance
zip – compression flag
TarIO Module
class PIL.TarIO.TarIO(tarfile, file)
Bases: PIL.ContainerIO.ContainerIO

WalImageFile Module
PIL.WalImageFile.open(filename)
_binary Module
PIL._binary.i16be(c, o=0)
PIL._binary.i16le(c, o=0)
Converts a 2-bytes (16 bits) string to an integer.

c: string containing bytes to convert o: offset of bytes to convert in string

PIL._binary.i32be(c, o=0)
PIL._binary.i32le(c, o=0)
Converts a 4-bytes (32 bits) string to an integer.

c: string containing bytes to convert o: offset of bytes to convert in string

PIL._binary.i8(c)
PIL._binary.o16be(i)
PIL._binary.o16le(i)
PIL._binary.o32be(i)
PIL._binary.o32le(i)
PIL._binary.o8(i)
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 16:21:08 | 显示全部楼层
PyAccess Module
The PyAccess module provides a CFFI/Python implementation of the PixelAccess Class. This implementation is far faster on PyPy than the PixelAccess version.

Note

Accessing individual pixels is fairly slow. If you are looping over all of the pixels in an image, there is likely a faster way using other parts of the Pillow API.
Example
The following script loads an image, accesses one pixel from it, then changes it.

from PIL import Image
im = Image.open('hopper.jpg')
px = im.load()
print (px[4,4])
px[4,4] = (0,0,0)
print (px[4,4])
Results in the following:

(23, 24, 68)
(0, 0, 0)
PyAccess Class
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 15:14:00 | 显示全部楼层
OleFileIO Module
The OleFileIO module reads Microsoft OLE2 files (also called Structured Storage or Microsoft Compound Document File Format), such as Microsoft Office documents, Image Composer and FlashPix files, and Outlook messages.

This module is the OleFileIO_PL project by Philippe Lagadec, v0.42, merged back into Pillow.

How to use this module
For more information, see also the file PIL/OleFileIO.py, sample code at the end of the module itself, and docstrings within the code.

About the structure of OLE files
An OLE file can be seen as a mini file system or a Zip archive: It contains streams of data that look like files embedded within the OLE file. Each stream has a name. For example, the main stream of a MS Word document containing its text is named “WordDocument”.

An OLE file can also contain storages. A storage is a folder that contains streams or other storages. For example, a MS Word document with VBA macros has a storage called “Macros”.

Special streams can contain properties. A property is a specific value that can be used to store information such as the metadata of a document (title, author, creation date, etc). Property stream names usually start with the character ‘05’.

For example, a typical MS Word document may look like this:

\x05DocumentSummaryInformation (stream)
\x05SummaryInformation (stream)
WordDocument (stream)
Macros (storage)
    PROJECT (stream)
    PROJECTwm (stream)
    VBA (storage)
        Module1 (stream)
        ThisDocument (stream)
        _VBA_PROJECT (stream)
        dir (stream)
ObjectPool (storage)
Test if a file is an OLE container
Use isOleFile to check if the first bytes of the file contain the Magic for OLE files, before opening it. isOleFile returns True if it is an OLE file, False otherwise.

assert OleFileIO.isOleFile('myfile.doc')
Open an OLE file from disk
Create an OleFileIO object with the file path as parameter:

ole = OleFileIO.OleFileIO('myfile.doc')
Open an OLE file from a file-like object
This is useful if the file is not on disk, e.g. already stored in a string or as a file-like object.

ole = OleFileIO.OleFileIO(f)
For example the code below reads a file into a string, then uses BytesIO to turn it into a file-like object.

data = open('myfile.doc', 'rb').read()
f = io.BytesIO(data) # or StringIO.StringIO for Python 2.x
ole = OleFileIO.OleFileIO(f)
How to handle malformed OLE files
By default, the parser is configured to be as robust and permissive as possible, allowing to parse most malformed OLE files. Only fatal errors will raise an exception. It is possible to tell the parser to be more strict in order to raise exceptions for files that do not fully conform to the OLE specifications, using the raise_defect option:

ole = OleFileIO.OleFileIO('myfile.doc', raise_defects=DEFECT_INCORRECT)
When the parsing is done, the list of non-fatal issues detected is available as a list in the parsing_issues attribute of the OleFileIO object:

print('Non-fatal issues raised during parsing:')
if ole.parsing_issues:
    for exctype, msg in ole.parsing_issues:
        print('- %s: %s' % (exctype.__name__, msg))
else:
    print('None')
Syntax for stream and storage path
Two different syntaxes are allowed for methods that need or return the path of streams and storages:

Either a list of strings including all the storages from the root up to the stream/storage name. For example a stream called “WordDocument” at the root will have [‘WordDocument’] as full path. A stream called “ThisDocument” located in the storage “Macros/VBA” will be [‘Macros’, ‘VBA’, ‘ThisDocument’]. This is the original syntax from PIL. While hard to read and not very convenient, this syntax works in all cases.
Or a single string with slashes to separate storage and stream names (similar to the Unix path syntax). The previous examples would be ‘WordDocument’ and ‘Macros/VBA/ThisDocument’. This syntax is easier, but may fail if a stream or storage name contains a slash.
Both are case-insensitive.

Switching between the two is easy:

slash_path = '/'.join(list_path)
list_path  = slash_path.split('/')
Get the list of streams
listdir() returns a list of all the streams contained in the OLE file, including those stored in storages. Each stream is listed itself as a list, as described above.

print(ole.listdir())
Sample result:

[['\x01CompObj'], ['\x05DocumentSummaryInformation'], ['\x05SummaryInformation']
, ['1Table'], ['Macros', 'PROJECT'], ['Macros', 'PROJECTwm'], ['Macros', 'VBA',
'Module1'], ['Macros', 'VBA', 'ThisDocument'], ['Macros', 'VBA', '_VBA_PROJECT']
, ['Macros', 'VBA', 'dir'], ['ObjectPool'], ['WordDocument']]
As an option it is possible to choose if storages should also be listed, with or without streams:

ole.listdir (streams=False, storages=True)
Test if known streams/storages exist:
exists(path) checks if a given stream or storage exists in the OLE file.

if ole.exists('worddocument'):
    print("This is a Word document.")
    if ole.exists('macros/vba'):
         print("This document seems to contain VBA macros.")
Read data from a stream
openstream(path) opens a stream as a file-like object.

The following example extracts the “Pictures” stream from a PPT file:

pics = ole.openstream('Pictures')
data = pics.read()
Get information about a stream/storage
Several methods can provide the size, type and timestamps of a given stream/storage:

get_size(path) returns the size of a stream in bytes:

s = ole.get_size('WordDocument')
get_type(path) returns the type of a stream/storage, as one of the following constants: STGTY_STREAM for a stream, STGTY_STORAGE for a storage, STGTY_ROOT for the root entry, and False for a non existing path.

t = ole.get_type('WordDocument')
get_ctime(path) and get_mtime(path) return the creation and modification timestamps of a stream/storage, as a Python datetime object with UTC timezone. Please note that these timestamps are only present if the application that created the OLE file explicitly stored them, which is rarely the case. When not present, these methods return None.

c = ole.get_ctime('WordDocument')
m = ole.get_mtime('WordDocument')
The root storage is a special case: You can get its creation and modification timestamps using the OleFileIO.root attribute:

c = ole.root.getctime()
m = ole.root.getmtime()
Extract metadata
get_metadata() will check if standard property streams exist, parse all the properties they contain, and return an OleMetadata object with the found properties as attributes.

meta = ole.get_metadata()
print('Author:', meta.author)
print('Title:', meta.title)
print('Creation date:', meta.create_time)
# print all metadata:
meta.dump()
Available attributes include:

codepage, title, subject, author, keywords, comments, template,
last_saved_by, revision_number, total_edit_time, last_printed, create_time,
last_saved_time, num_pages, num_words, num_chars, thumbnail,
creating_application, security, codepage_doc, category, presentation_target,
bytes, lines, paragraphs, slides, notes, hidden_slides, mm_clips,
scale_crop, heading_pairs, titles_of_parts, manager, company, links_dirty,
chars_with_spaces, unused, shared_doc, link_base, hlinks, hlinks_changed,
version, dig_sig, content_type, content_status, language, doc_version
See the source code of the OleMetadata class for more information.

Parse a property stream
get_properties(path) can be used to parse any property stream that is not handled by get_metadata. It returns a dictionary indexed by integers. Each integer is the index of the property, pointing to its value. For example in the standard property stream ‘05SummaryInformation’, the document title is property #2, and the subject is #3.

p = ole.getproperties('specialprops')
By default as in the original PIL version, timestamp properties are converted into a number of seconds since Jan 1,1601. With the option convert_time, you can obtain more convenient Python datetime objects (UTC timezone). If some time properties should not be converted (such as total editing time in ‘05SummaryInformation’), the list of indexes can be passed as no_conversion:

p = ole.getproperties('specialprops', convert_time=True, no_conversion=[10])
Close the OLE file
Unless your application is a simple script that terminates after processing an OLE file, do not forget to close each OleFileIO object after parsing to close the file on disk.

ole.close()
Use OleFileIO as a script
OleFileIO can also be used as a script from the command-line to display the structure of an OLE file and its metadata, for example:

PIL/OleFileIO.py myfile.doc
You can use the option -c to check that all streams can be read fully, and -d to generate very verbose debugging information.

How to contribute
The code is available in a Mercurial repository on bitbucket. You may use it to submit enhancements or to report any issue.

If you would like to help us improve this module, or simply provide feedback, please contact me. You can help in many ways:

test this module on different platforms / Python versions
find and report bugs
improve documentation, code samples, docstrings
write unittest test cases
provide tricky malformed files
How to report bugs
To report a bug, for example a normal file which is not parsed correctly, please use the issue reporting page, or if you prefer to do it privately, use this contact form. Please provide all the information about the context and how to reproduce the bug.

If possible please join the debugging output of OleFileIO. For this, launch the following command :

PIL/OleFileIO.py -d -c file >debug.txt
Classes and Methods
class PIL.OleFileIO.OleFileIO(filename=None, raise_defects=40, write_mode=False, debug=False, path_encoding='utf-8')
Bases: object

OLE container object

This class encapsulates the interface to an OLE 2 structured storage file. Use the listdir() and openstream() methods to access the contents of this file.

Object names are given as a list of strings, one for each subentry level. The root entry should be omitted. For example, the following code extracts all image streams from a Microsoft Image Composer file:

ole = OleFileIO("fan.mic")

for entry in ole.listdir():
    if entry[1:2] == "Image":
        fin = ole.openstream(entry)
        fout = open(entry[0:1], "wb")
        while True:
            s = fin.read(8192)
            if not s:
                break
            fout.write(s)
You can use the viewer application provided with the Python Imaging Library to view the resulting files (which happens to be standard TIFF files).

close()
close the OLE file, to release the file object

dumpdirectory()
Dump directory (for debugging only)

dumpfat(fat, firstindex=0)
Displays a part of FAT in human-readable form for debugging purpose

dumpsect(sector, firstindex=0)
Displays a sector in a human-readable form, for debugging purpose.

exists(filename)
Test if given filename exists as a stream or a storage in the OLE container. Note: filename is case-insensitive.

Parameters:        filename – path of stream in storage tree. (see openstream for syntax)
Returns:        True if object exist, else False.
get_metadata()
Parse standard properties streams, return an OleMetadata object containing all the available metadata. (also stored in the metadata attribute of the OleFileIO object)

new in version 0.25

get_rootentry_name()
Return root entry name. Should usually be ‘Root Entry’ or ‘R’ in most implementations.

get_size(filename)
Return size of a stream in the OLE container, in bytes.

Parameters:       
filename – path of stream in storage tree (see openstream for syntax)

Returns:       
size in bytes (long integer)

Raises:       
IOError – if file not found
TypeError – if this is not a stream.
get_type(filename)
Test if given filename exists as a stream or a storage in the OLE container, and return its type.

Parameters:        filename – path of stream in storage tree. (see openstream for syntax)
Returns:        False if object does not exist, its entry type (>0) otherwise:
STGTY_STREAM: a stream
STGTY_STORAGE: a storage
STGTY_ROOT: the root entry
getctime(filename)
Return creation time of a stream/storage.

Parameters:        filename – path of stream/storage in storage tree. (see openstream for syntax)
Returns:        None if creation time is null, a python datetime object otherwise (UTC timezone)
new in version 0.26

getmtime(filename)
Return modification time of a stream/storage.

Parameters:        filename – path of stream/storage in storage tree. (see openstream for syntax)
Returns:        None if modification time is null, a python datetime object otherwise (UTC timezone)
new in version 0.26

getproperties(filename, convert_time=False, no_conversion=None)
Return properties described in substream.

Parameters:       
filename – path of stream in storage tree (see openstream for syntax)
convert_time – bool, if True timestamps will be converted to Python datetime
no_conversion – None or list of int, timestamps not to be converted (for example total editing time is not a real timestamp)
Returns:       
a dictionary of values indexed by id (integer)

getsect(sect)
Read given sector from file on disk.

Parameters:        sect – int, sector index
Returns:        a string containing the sector data.
listdir(streams=True, storages=False)
Return a list of streams and/or storages stored in this file

Parameters:       
streams – bool, include streams if True (True by default) - new in v0.26
storages – bool, include storages if True (False by default) - new in v0.26 (note: the root storage is never included)
Returns:       
list of stream and/or storage paths

loaddirectory(sect)
Load the directory.

Parameters:        sect – sector index of directory stream.
loadfat(header)
Load the FAT table.

loadfat_sect(sect)
Adds the indexes of the given sector to the FAT

Parameters:        sect – string containing the first FAT sector, or array of long integers
Returns:        index of last FAT sector.
loadminifat()
Load the MiniFAT table.

open(filename, write_mode=False)
Open an OLE2 file in read-only or read/write mode. Read and parse the header, FAT and directory.

Parameters:       
filename –
string-like or file-like object, OLE file to parse

if filename is a string smaller than 1536 bytes, it is the path of the file to open. (bytes or unicode string)
if filename is a string longer than 1535 bytes, it is parsed as the content of an OLE file in memory. (bytes type only)
if filename is a file-like object (with read, seek and tell methods), it is parsed as-is.
write_mode – bool, if True the file is opened in read/write mode instead of read-only by default. (ignored if filename is not a path)
openstream(filename)
Open a stream as a read-only file object (BytesIO). Note: filename is case-insensitive.

Parameters:        filename –
path of stream in storage tree (except root entry), either:

a string using Unix path syntax, for example: ‘storage_1/storage_1.2/stream’
or a list of storage filenames, path to the desired stream/storage. Example: [‘storage_1’, ‘storage_1.2’, ‘stream’]
Returns:        file object (read-only)
Raises:        IOError – if filename not found, or if this is not a stream.
raise_defect(defect_level, message, exception_type=<type 'exceptions.IOError'>)
This method should be called for any defect found during file parsing. It may raise an IOError exception according to the minimal level chosen for the OleFileIO object.

Parameters:       
defect_level –
defect level, possible values are:

DEFECT_UNSURE : a case which looks weird, but not sure it’s a defect
DEFECT_POTENTIAL : a potential defect
DEFECT_INCORRECT : an error according to specifications, but parsing can go on
DEFECT_FATAL : an error which cannot be ignored, parsing is impossible
message – string describing the defect, used with raised exception.
exception_type – exception class to be raised, IOError by default
sect2array(sect)
convert a sector to an array of 32 bits unsigned integers, swapping bytes on big endian CPUs such as PowerPC (old Macs)

write_sect(sect, data, padding='\x00')
Write given sector to file on disk.

Parameters:       
sect – int, sector index
data – bytes, sector data
padding – single byte, padding character if data < sector size
write_stream(stream_name, data)
Write a stream to disk. For now, it is only possible to replace an existing stream by data of the same size.

Parameters:       
stream_name –
path of stream in storage tree (except root entry), either:

a string using Unix path syntax, for example: ‘storage_1/storage_1.2/stream’
or a list of storage filenames, path to the desired stream/storage. Example: [‘storage_1’, ‘storage_1.2’, ‘stream’]
data – bytes, data to be written, must be the same size as the original stream.
class PIL.OleFileIO.OleMetadata
Bases: object

class to parse and store metadata from standard properties of OLE files.

Available attributes: codepage, title, subject, author, keywords, comments, template, last_saved_by, revision_number, total_edit_time, last_printed, create_time, last_saved_time, num_pages, num_words, num_chars, thumbnail, creating_application, security, codepage_doc, category, presentation_target, bytes, lines, paragraphs, slides, notes, hidden_slides, mm_clips, scale_crop, heading_pairs, titles_of_parts, manager, company, links_dirty, chars_with_spaces, unused, shared_doc, link_base, hlinks, hlinks_changed, version, dig_sig, content_type, content_status, language, doc_version

Note: an attribute is set to None when not present in the properties of the OLE file.

References for SummaryInformation stream: - http://msdn.microsoft.com/en-us/library/dd942545.aspx - http://msdn.microsoft.com/en-us/library/dd925819%28v=office.12%29.aspx - http://msdn.microsoft.com/en-us/library/windows/desktop/aa380376%28v=vs.85%29.aspx - http://msdn.microsoft.com/en-us/library/aa372045.aspx - http://sedna-soft.de/summary-information-stream/ - http://poi.apache.org/apidocs/org/apache/poi/hpsf/SummaryInformation.html

References for DocumentSummaryInformation stream: - http://msdn.microsoft.com/en-us/library/dd945671%28v=office.12%29.aspx - http://msdn.microsoft.com/en-us/library/windows/desktop/aa380374%28v=vs.85%29.aspx - http://poi.apache.org/apidocs/org/apache/poi/hpsf/DocumentSummaryInformation.html

new in version 0.25

DOCSUM_ATTRIBS = ['codepage_doc', 'category', 'presentation_target', 'bytes', 'lines', 'paragraphs', 'slides', 'notes', 'hidden_slides', 'mm_clips', 'scale_crop', 'heading_pairs', 'titles_of_parts', 'manager', 'company', 'links_dirty', 'chars_with_spaces', 'unused', 'shared_doc', 'link_base', 'hlinks', 'hlinks_changed', 'version', 'dig_sig', 'content_type', 'content_status', 'language', 'doc_version']
SUMMARY_ATTRIBS = ['codepage', 'title', 'subject', 'author', 'keywords', 'comments', 'template', 'last_saved_by', 'revision_number', 'total_edit_time', 'last_printed', 'create_time', 'last_saved_time', 'num_pages', 'num_words', 'num_chars', 'thumbnail', 'creating_application', 'security']
dump()
Dump all metadata, for debugging purposes.

parse_properties(olefile)
Parse standard properties of an OLE file, from the streams “SummaryInformation” and “DocumentSummaryInformation”, if present. Properties are converted to strings, integers or python datetime objects. If a property is not present, its value is set to None.

PIL.OleFileIO.debug(msg)
PIL.OleFileIO.debug_pass(msg)
PIL.OleFileIO.debug_print(msg)
PIL.OleFileIO.filetime2datetime(filetime)
convert FILETIME (64 bits int) to Python datetime.datetime

PIL.OleFileIO.i16(c, o=0)
Converts a 2-bytes (16 bits) string to an integer.

c: string containing bytes to convert o: offset of bytes to convert in string

PIL.OleFileIO.i32(c, o=0)
Converts a 4-bytes (32 bits) string to an integer.

c: string containing bytes to convert o: offset of bytes to convert in string

PIL.OleFileIO.i8(c)
PIL.OleFileIO.isOleFile(filename)
Test if a file is an OLE container (according to the magic bytes in its header).

Parameters:        filename –
string-like or file-like object, OLE file to parse

if filename is a string smaller than 1536 bytes, it is the path of the file to open. (bytes or unicode string)
if filename is a string longer than 1535 bytes, it is parsed as the content of an OLE file in memory. (bytes type only)
if filename is a file-like object (with read and seek methods), it is parsed as-is.
Returns:        True if OLE, False otherwise.
PIL.OleFileIO.set_debug_mode(debug_mode)
Set debug mode on or off, to control display of debugging messages. :param mode: True or False
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 15:11:07 | 显示全部楼层
ExifTags Module
The ExifTags module exposes two dictionaries which provide constants and clear-text names for various well-known EXIF tags.

class PIL.ExifTags.TAGS
The TAG dictionary maps 16-bit integer EXIF tag enumerations to descriptive string names. For instance:

>>> from PIL.ExifTags import TAGS
>>> TAGS[0x010e]
'ImageDescription'
class PIL.ExifTags.GPSTAGS
The GPSTAGS dictionary maps 8-bit integer EXIF gps enumerations to descriptive string names. For instance:

>>> from PIL.ExifTags import GPSTAGS
>>> GPSTAGS[20]
'GPSDestLatitude'
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 15:10:17 | 显示全部楼层
ImageWin Module (Windows-only)
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:

from PIL import ImageWin

dib = ImageWin.Dib(...)

hwnd = ImageWin.HWND(widget.winfo_id())
dib.draw(hwnd, xy)
class PIL.ImageWin.Dib(image, size=None)
A Windows bitmap with the given mode and size. The mode can be one of “1”, “L”, “P”, or “RGB”.

If the display requires a palette, this constructor creates a suitable palette and associates it with the image. For an “L” image, 128 greylevels are allocated. For an “RGB” image, a 6x6x6 colour cube is used, together with 20 greylevels.

To make sure that palettes work properly under Windows, you must call the palette method upon certain events from Windows.

Parameters:       
image – Either a PIL image, or a mode string. If a mode string is used, a size must also be given. The mode can be one of “1”, “L”, “P”, or “RGB”.
size – If the first argument is a mode string, this defines the size of the image.
draw(handle, dst, src=None)
Same as expose, but allows you to specify where to draw the image, and what part of it to draw.

The destination and source areas are given as 4-tuple rectangles. If the source is omitted, the entire image is copied. If the source and the destination have different sizes, the image is resized as necessary.

expose(handle)
Copy the bitmap contents to a device context.

Parameters:        handle – Device context (HDC), cast to a Python integer, or an HDC or HWND instance. In PythonWin, you can use the CDC.GetHandleAttrib() to get a suitable handle.
frombytes(buffer)
Load display memory contents from byte data.

Parameters:        buffer – A buffer containing display data (usually data returned from <b>tobytes</b>)
paste(im, box=None)
Paste a PIL image into the bitmap image.

Parameters:       
im – A PIL image. The size must match the target region. If the mode does not match, the image is converted to the mode of the bitmap image.
box – A 4-tuple defining the left, upper, right, and lower pixel coordinate. If None is given instead of a tuple, all of the image is assumed.
query_palette(handle)
Installs the palette associated with the image in the given device context.

This method should be called upon QUERYNEWPALETTE and PALETTECHANGED events from Windows. If this method returns a non-zero value, one or more display palette entries were changed, and the image should be redrawn.

Parameters:        handle – Device context (HDC), cast to a Python integer, or an HDC or HWND instance.
Returns:        A true value if one or more entries were changed (this indicates that the image should be redrawn).
tobytes()
Copy display memory contents to bytes object.

Returns:        A bytes object containing display data.
class PIL.ImageWin.HDC(dc)
Wraps an HDC integer. The resulting object can be passed to the draw() and expose() methods.

class PIL.ImageWin.HWND(wnd)
Wraps an HWND integer. The resulting object can be passed to the draw() and expose() methods, instead of a DC.
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 15:08:53 | 显示全部楼层
The ImageTk module contains support to create and modify Tkinter BitmapImage and PhotoImage objects from PIL images.

For examples, see the demo programs in the Scripts directory.

class PIL.ImageTk.BitmapImage(image=None, **kw)
A Tkinter-compatible bitmap image. This can be used everywhere Tkinter expects an image object.

The given image must have mode “1”. Pixels having value 0 are treated as transparent. Options, if any, are passed on to Tkinter. The most commonly used option is foreground, which is used to specify the color for the non-transparent parts. See the Tkinter documentation for information on how to specify colours.

Parameters:        image – A PIL image.
height()
Get the height of the image.

Returns:        The height, in pixels.
width()
Get the width of the image.

Returns:        The width, in pixels.
class PIL.ImageTk.PhotoImage(image=None, size=None, **kw)
A Tkinter-compatible photo image. This can be used everywhere Tkinter expects an image object. If the image is an RGBA image, pixels having alpha 0 are treated as transparent.

The constructor takes either a PIL image, or a mode and a size. Alternatively, you can use the file or data options to initialize the photo image object.

Parameters:       
image – Either a PIL image, or a mode string. If a mode string is used, a size must also be given.
size – If the first argument is a mode string, this defines the size of the image.
file – A filename to load the image from (using Image.open(file)).
data – An 8-bit string containing image data (as loaded from an image file).
height()
Get the height of the image.

Returns:        The height, in pixels.
paste(im, box=None)
Paste a PIL image into the photo image. Note that this can be very slow if the photo image is displayed.

Parameters:       
im – A PIL image. The size must match the target region. If the mode does not match, the image is converted to the mode of the bitmap image.
box – A 4-tuple defining the left, upper, right, and lower pixel coordinate. If None is given instead of a tuple, all of the image is assumed.
width()
Get the width of the image.

Returns:        The width, in pixels.
Next  Previous
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 15:08:22 | 显示全部楼层
ImageStat Module
The ImageStat module calculates global statistics for an image, or for a region of an image.

class PIL.ImageStat.Stat(image_or_list, mask=None)
Calculate statistics for the given image. If a mask is included, only the regions covered by that mask are included in the statistics. You can also pass in a previously calculated histogram.

Parameters:       
image – A PIL image, or a precalculated histogram.
mask – An optional mask.
extrema
Min/max values for each band in the image.

count
Total number of pixels for each band in the image.

sum
Sum of all pixels for each band in the image.

sum2
Squared sum of all pixels for each band in the image.

mean
Average (arithmetic mean) pixel level for each band in the image.

median
Median pixel level for each band in the image.

rms
RMS (root-mean-square) for each band in the image.

var
Variance for each band in the image.

stddev
Standard deviation for each band in the image.
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 15:07:25 | 显示全部楼层
ImageSequence Module
The ImageSequence module contains a wrapper class that lets you iterate over the frames of an image sequence.

Extracting frames from an animation
from PIL import Image, ImageSequence

im = Image.open("animation.fli")

index = 1
for frame in ImageSequence.Iterator(im):
    frame.save("frame%d.png" % index)
    index = index + 1
The Iterator class
class PIL.ImageSequence.Iterator(im)
This class implements an iterator object that can be used to loop over an image sequence.

You can use the [] operator to access elements by index. This operator will raise an IndexError if you try to access a nonexistent frame.

Parameters:        im – An image object.
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 15:05:19 | 显示全部楼层
ImageQt Module
The ImageQt module contains support for creating PyQt4 or PyQt5 QImage objects from PIL images.

New in version 1.1.6.

class ImageQt.ImageQt(image)
Creates an ImageQt object from a PIL Image object. This class is a subclass of QtGui.QImage, which means that you can pass the resulting objects directly to PyQt4/5 API functions and methods.

This operation is currently supported for mode 1, L, P, RGB, and RGBA images. To handle other modes, you need to convert the image first.

Next  Previous
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 15:04:32 | 显示全部楼层
ImagePath Module
The ImagePath module is used to store and manipulate 2-dimensional vector data. Path objects can be passed to the methods on the ImageDraw module.

class PIL.ImagePath.Path
A path object. The coordinate list can be any sequence object containing either 2-tuples [(x, y), …] or numeric values [x, y, …].

You can also create a path object from another path object.

In 1.1.6 and later, you can also pass in any object that implements Python’s buffer API. The buffer should provide read access, and contain C floats in machine byte order.

The path object implements most parts of the Python sequence interface, and behaves like a list of (x, y) pairs. You can use len(), item access, and slicing as usual. However, the current version does not support slice assignment, or item and slice deletion.

Parameters:        xy – A sequence. The sequence can contain 2-tuples [(x, y), ...] or a flat list of numbers [x, y, ...].
PIL.ImagePath.Path.compact(distance=2)
Compacts the path, by removing points that are close to each other. This method modifies the path in place, and returns the number of points left in the path.

distance is measured as Manhattan distance and defaults to two pixels.

PIL.ImagePath.Path.getbbox()
Gets the bounding box of the path.

Returns:        (x0, y0, x1, y1)
PIL.ImagePath.Path.map(function)
Maps the path through a function.

PIL.ImagePath.Path.tolist(flat=0)
Converts the path to a Python list [(x, y), …].

Parameters:        flat – By default, this function returns a list of 2-tuples [(x, y), ...]. If this argument is True, it returns a flat list [x, y, ...] instead.
Returns:        A list of coordinates. See flat.
PIL.ImagePath.Path.transform(matrix)
Transforms the path in place, using an affine transform. The matrix is a 6-tuple (a, b, c, d, e, f), and each point is mapped as follows:

xOut = xIn * a + yIn * b + c
yOut = xIn * d + yIn * e + f
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 15:01:52 | 显示全部楼层
ImagePalette Module
The ImagePalette module contains a class of the same name to represent the color palette of palette mapped images.

Note

This module was never well-documented. It hasn’t changed since 2001, though, so it’s probably safe for you to read the source code and puzzle out the internals if you need to.

The ImagePalette class has several methods, but they are all marked as “experimental.” Read that as you will. The [source] link is there for a reason.
class PIL.ImagePalette.ImagePalette(mode='RGB', palette=None, size=0)
Color palette for palette mapped images

Parameters:       
mode – The mode to use for the Palette. See: Modes. Defaults to “RGB”
palette – An optional palette. If given, it must be a bytearray, an array or a list of ints between 0-255 and of length size times the number of colors in mode. The list must be aligned by channel (All R values must be contiguous in the list before G and B values.) Defaults to 0 through 255 per channel.
size – An optional palette size. If given, it cannot be equal to or greater than 256. Defaults to 0.
getcolor(color)
Given an rgb tuple, allocate palette entry.

Warning

This method is experimental.

getdata()
Get palette contents in format suitable # for the low-level im.putpalette primitive.

Warning

This method is experimental.

save(fp)
Save palette to text file.

Warning

This method is experimental.

tobytes()
Convert palette to bytes.

Warning

This method is experimental.

tostring()
Convert palette to bytes.

Warning

This method is experimental.
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 14:12:22 | 显示全部楼层
智商负 发表于 2016-11-8 12:25
英文太差看不懂,缩略图什么的

在公司开国外网站很快,先把原文下载下来,有时间我会挑重点和常用的函数做翻译
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 13:13:55 | 显示全部楼层
ImageOps Module
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.

Only bug fixes have been added since the Pillow fork.

New in version 1.1.3.

PIL.ImageOps.autocontrast(image, cutoff=0, ignore=None)
Maximize (normalize) image contrast. This function calculates a histogram of the input image, removes cutoff percent of the lightest and darkest pixels from the histogram, and remaps the image so that the darkest pixel becomes black (0), and the lightest becomes white (255).

Parameters:       
image – The image to process.
cutoff – How many percent to cut off from the histogram.
ignore – The background pixel value (use None for no background).
Returns:       
An image.

PIL.ImageOps.colorize(image, black, white)
Colorize grayscale image. The black and white arguments should be RGB tuples; this function calculates a color wedge mapping all black pixels in the source image to the first color, and all white pixels to the second color.

Parameters:       
image – The image to colorize.
black – The color to use for black input pixels.
white – The color to use for white input pixels.
Returns:       
An image.

PIL.ImageOps.crop(image, border=0)
Remove border from image. The same amount of pixels are removed from all four sides. This function works on all image modes.

See also

crop()

Parameters:       
image – The image to crop.
border – The number of pixels to remove.
Returns:       
An image.

PIL.ImageOps.deform(image, deformer, resample=2)
Deform the image.

Parameters:       
image – The image to deform.
deformer – A deformer object. Any object that implements a getmesh method can be used.
resample – What resampling filter to use.
Returns:       
An image.

PIL.ImageOps.equalize(image, mask=None)
Equalize the image histogram. This function applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image.

Parameters:       
image – The image to equalize.
mask – An optional mask. If given, only the pixels selected by the mask are included in the analysis.
Returns:       
An image.

PIL.ImageOps.expand(image, border=0, fill=0)
Add border to the image

Parameters:       
image – The image to expand.
border – Border width, in pixels.
fill – Pixel fill value (a color value). Default is 0 (black).
Returns:       
An image.

PIL.ImageOps.fit(image, size, method=0, bleed=0.0, centering=(0.5, 0.5))
Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size.

This function was contributed by Kevin Cazabon.

Parameters:       
size – The requested output size in pixels, given as a (width, height) tuple.
method – What resampling method to use. Default is PIL.Image.NEAREST.
bleed – Remove a border around the outside of the image (from all four edges. The value is a decimal percentage (use 0.01 for one percent). The default value is 0 (no border).
centering – Control the cropping position. Use (0.5, 0.5) for center cropping (e.g. if cropping the width, take 50% off of the left side, and therefore 50% off the right side). (0.0, 0.0) will crop from the top left corner (i.e. if cropping the width, take all of the crop off of the right side, and if cropping the height, take all of it off the bottom). (1.0, 0.0) will crop from the bottom left corner, etc. (i.e. if cropping the width, take all of the crop off the left side, and if cropping the height take none from the top, and therefore all off the bottom).
Returns:       
An image.

PIL.ImageOps.flip(image)
Flip the image vertically (top to bottom).

Parameters:        image – The image to flip.
Returns:        An image.
PIL.ImageOps.grayscale(image)
Convert the image to grayscale.

Parameters:        image – The image to convert.
Returns:        An image.
PIL.ImageOps.invert(image)
Invert (negate) the image.

Parameters:        image – The image to invert.
Returns:        An image.
PIL.ImageOps.mirror(image)
Flip image horizontally (left to right).

Parameters:        image – The image to mirror.
Returns:        An image.
PIL.ImageOps.posterize(image, bits)
Reduce the number of bits for each color channel.

Parameters:       
image – The image to posterize.
bits – The number of bits to keep for each channel (1-8).
Returns:       
An image.

PIL.ImageOps.solarize(image, threshold=128)
Invert all pixel values above a threshold.

Parameters:       
image – The image to solarize.
threshold – All pixels above this greyscale level are inverted.
Returns:       
An image.
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 13:09:30 | 显示全部楼层
ImageMorph Module
The ImageMorph module provides morphology operations on images.

class PIL.ImageMorph.LutBuilder(patterns=None, op_name=None)
Bases: object

A class for building a MorphLut from a descriptive language

The input patterns is a list of a strings sequences like these:

4:(...
   .1.
   111)->1
(whitespaces including linebreaks are ignored). The option 4 describes a series of symmetry operations (in this case a 4-rotation), the pattern is described by:

. or X - Ignore
1 - Pixel is on
0 - Pixel is off
The result of the operation is described after “->” string.

The default is to return the current pixel value, which is returned if no other match is found.

Operations:

4 - 4 way rotation
N - Negate
1 - Dummy op for no other operation (an op must always be given)
M - Mirroring
Example:

lb = LutBuilder(patterns = ["4:(... .1. 111)->1"])
lut = lb.build_lut()
add_patterns(patterns)
build_default_lut()
build_lut()
Compile all patterns into a morphology lut.

TBD :Build based on (file) morphlut:modify_lut

get_lut()
class PIL.ImageMorph.MorphOp(lut=None, op_name=None, patterns=None)
Bases: object

A class for binary morphological operators

apply(image)
Run a single morphological operation on an image

Returns a tuple of the number of changed pixels and the morphed image

get_on_pixels(image)
Get a list of all turned on pixels in a binary image

Returns a list of tuples of (x,y) coordinates of all matching pixels.

load_lut(filename)
Load an operator from an mrl file

match(image)
Get a list of coordinates matching the morphological operation on an image.

Returns a list of tuples of (x,y) coordinates of all matching pixels.

save_lut(filename)
Save an operator to an mrl file

set_lut(lut)
Set the lut from an external source

Next  Previous
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 13:04:24 | 显示全部楼层
ImageMath Module
The ImageMath module can be used to evaluate “image expressions”. The module provides a single eval function, which takes an expression string and one or more images.

Example: Using the ImageMath module
from PIL import Image, ImageMath

im1 = Image.open("image1.jpg")
im2 = Image.open("image2.jpg")

out = ImageMath.eval("convert(min(a, b), 'L')", a=im1, b=im2)
out.save("result.png")
PIL.ImageMath.eval(expression, environment)
Evaluate expression in the given environment.

In the current version, ImageMath only supports single-layer images. To process multi-band images, use the split() method or merge() function.

Parameters:       
expression – A string which uses the standard Python expression syntax. In addition to the standard operators, you can also use the functions described below.
environment – A dictionary that maps image names to Image instances. You can use one or more keyword arguments instead of a dictionary, as shown in the above example. Note that the names must be valid Python identifiers.
Returns:       
An image, an integer value, a floating point value, or a pixel tuple, depending on the expression.

Expression syntax
Expressions are standard Python expressions, but they’re evaluated in a non-standard environment. You can use PIL methods as usual, plus the following set of operators and functions:

Standard Operators
You can use standard arithmetical operators for addition (+), subtraction (-), multiplication (*), and division (/).

The module also supports unary minus (-), modulo (%), and power (**) operators.

Note that all operations are done with 32-bit integers or 32-bit floating point values, as necessary. For example, if you add two 8-bit images, the result will be a 32-bit integer image. If you add a floating point constant to an 8-bit image, the result will be a 32-bit floating point image.

You can force conversion using the convert(), float(), and int() functions described below.

Bitwise Operators
The module also provides operations that operate on individual bits. This includes and (&), or (|), and exclusive or (^). You can also invert (~) all pixel bits.

Note that the operands are converted to 32-bit signed integers before the bitwise operation is applied. This means that you’ll get negative values if you invert an ordinary greyscale image. You can use the and (&) operator to mask off unwanted bits.

Bitwise operators don’t work on floating point images.

Logical Operators
Logical operators like and, or, and not work on entire images, rather than individual pixels.

An empty image (all pixels zero) is treated as false. All other images are treated as true.

Note that and and or return the last evaluated operand, while not always returns a boolean value.

Built-in Functions
These functions are applied to each individual pixel.

abs(image)
Absolute value.

convert(image, mode)
Convert image to the given mode. The mode must be given as a string constant.

float(image)
Convert image to 32-bit floating point. This is equivalent to convert(image, “F”).

int(image)
Convert image to 32-bit integer. This is equivalent to convert(image, “I”).

Note that 1-bit and 8-bit images are automatically converted to 32-bit integers if necessary to get a correct result.

max(image1, image2)
Maximum value.

min(image1, image2)
Minimum value.
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-11-8 12:25:56 | 显示全部楼层
英文太差看不懂,缩略图什么的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-7 03:40

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表