鱼C论坛

 找回密码
 立即注册
查看: 4562|回复: 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
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-11-8 11:58:52 | 显示全部楼层
ImageChops (“Channel Operations”) Module
The ImageChops module contains a number of arithmetical image operations, called channel operations (“chops”). These can be used for various purposes, including special effects, image compositions, algorithmic painting, and more.

For more pre-made operations, see ImageOps.

At this time, most channel operations are only implemented for 8-bit images (e.g. “L” and “RGB”).

Functions
Most channel operations take one or two image arguments and returns a new image. Unless otherwise noted, the result of a channel operation is always clipped to the range 0 to MAX (which is 255 for all modes supported by the operations in this module).

PIL.ImageChops.add(image1, image2, scale=1.0, offset=0)
Adds two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset to 0.0.

out = ((image1 + image2) / scale + offset)
Return type:        Image
PIL.ImageChops.add_modulo(image1, image2)
Add two images, without clipping the result.

out = ((image1 + image2) % MAX)
Return type:        Image
PIL.ImageChops.blend(image1, image2, alpha)
Blend images using constant transparency weight. Alias for PIL.Image.Image.blend().

Return type:        Image
PIL.ImageChops.composite(image1, image2, mask)
Create composite using transparency mask. Alias for PIL.Image.Image.composite().

Return type:        Image
PIL.ImageChops.constant(image, value)
Fill a channel with a given grey level.

Return type:        Image
PIL.ImageChops.darker(image1, image2)
Compares the two images, pixel by pixel, and returns a new image containing the darker values.

out = min(image1, image2)
Return type:        Image
PIL.ImageChops.difference(image1, image2)
Returns the absolute value of the pixel-by-pixel difference between the two images.

out = abs(image1 - image2)
Return type:        Image
PIL.ImageChops.duplicate(image)
Copy a channel. Alias for PIL.Image.Image.copy().

Return type:        Image
PIL.ImageChops.invert(image)
Invert an image (channel).

out = MAX - image
Return type:        Image
PIL.ImageChops.lighter(image1, image2)
Compares the two images, pixel by pixel, and returns a new image containing the lighter values.

out = max(image1, image2)
Return type:        Image
PIL.ImageChops.logical_and(image1, image2)
Logical AND between two images.

out = ((image1 and image2) % MAX)
Return type:        Image
PIL.ImageChops.logical_or(image1, image2)
Logical OR between two images.

out = ((image1 or image2) % MAX)
Return type:        Image
PIL.ImageChops.multiply(image1, image2)
Superimposes two images on top of each other.

If you multiply an image with a solid black image, the result is black. If you multiply with a solid white image, the image is unaffected.

out = image1 * image2 / MAX
Return type:        Image
PIL.ImageChops.offset(image, xoffset, yoffset=None)
Returns a copy of the image where data has been offset by the given distances. Data wraps around the edges. If yoffset is omitted, it is assumed to be equal to xoffset.

Parameters:       
xoffset – The horizontal distance.
yoffset – The vertical distance. If omitted, both distances are set to the same value.
Return type:       
Image

PIL.ImageChops.screen(image1, image2)
Superimposes two inverted images on top of each other.

out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
Return type:        Image
PIL.ImageChops.subtract(image1, image2, scale=1.0, offset=0)
Subtracts two images, dividing the result by scale and adding the offset. If omitted, scale defaults to 1.0, and offset to 0.0.

out = ((image1 - image2) / scale + offset)
Return type:        Image
PIL.ImageChops.subtract_modulo(image1, image2)
Subtract two images, without clipping the result.

out = ((image1 - image2) % MAX)
Return type:        Image
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 11:59:23 | 显示全部楼层
ImageColor Module
The ImageColor module contains color tables and converters from CSS3-style color specifiers to RGB tuples. This module is used by PIL.Image.Image.new() and the ImageDraw module, among others.

Color Names
The ImageColor module supports the following string formats:

Hexadecimal color specifiers, given as #rgb or #rrggbb. For example, #ff0000 specifies pure red.
RGB functions, given as rgb(red, green, blue) where the color values are integers in the range 0 to 255. Alternatively, the color values can be given as three percentages (0% to 100%). For example, rgb(255,0,0) and rgb(100%,0%,0%) both specify pure red.
Hue-Saturation-Lightness (HSL) functions, given as hsl(hue, saturation%, lightness%) where hue is the color given as an angle between 0 and 360 (red=0, green=120, blue=240), saturation is a value between 0% and 100% (gray=0%, full color=100%), and lightness is a value between 0% and 100% (black=0%, normal=50%, white=100%). For example, hsl(0,100%,50%) is pure red.
Common HTML color names. The ImageColor module provides some 140 standard color names, based on the colors supported by the X Window system and most web browsers. color names are case insensitive. For example, red and Red both specify pure red.
Functions
PIL.ImageColor.getrgb(color)
Convert a color string to an RGB tuple. If the string cannot be parsed, this function raises a ValueError exception.
New in version 1.1.4.

Parameters:        color – A color string
Returns:        (red, green, blue[, alpha])
PIL.ImageColor.getcolor(color, mode)
Same as getrgb(), but converts the RGB value to a greyscale value if the mode is not color or a palette image. If the string cannot be parsed, this function raises a ValueError exception.

New in version 1.1.4.

Parameters:        color – A color string
Returns:        (graylevel [, alpha]) or (red, green, blue[, alpha])
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 12:00:02 | 显示全部楼层
ImageCms Module
The ImageCms module provides color profile management support using the LittleCMS2 color management engine, based on Kevin Cazabon’s PyCMS library.

exception PIL.ImageCms.PyCMSError
(pyCMS) Exception class. This is used for all errors in the pyCMS API.

PIL.ImageCms.applyTransform(im, transform, inPlace=0)
(pyCMS) Applies a transform to a given image.

If im.mode != transform.inMode, a PyCMSError is raised.

If inPlace == TRUE and transform.inMode != transform.outMode, a PyCMSError is raised.

If im.mode, transfer.inMode, or transfer.outMode is not supported by pyCMSdll or the profiles you used for the transform, a PyCMSError is raised.

If an error occurs while the transform is being applied, a PyCMSError is raised.

This function applies a pre-calculated transform (from ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles()) to an image. The transform can be used for multiple images, saving considerable calculation time if doing the same conversion multiple times.

If you want to modify im in-place instead of receiving a new image as the return value, set inPlace to TRUE. This can only be done if transform.inMode and transform.outMode are the same, because we can’t change the mode in-place (the buffer sizes for some modes are different). The default behavior is to return a new Image object of the same dimensions in mode transform.outMode.

Parameters:       
im – A PIL Image object, and im.mode must be the same as the inMode supported by the transform.
transform – A valid CmsTransform class object
inPlace – Bool (1 == True, 0 or None == False). If True, im is modified in place and None is returned, if False, a new Image object with the transform applied is returned (and im is not changed). The default is False.
Returns:       
Either None, or a new PIL Image object, depending on the value of inPlace. The profile will be returned in the image’s info[‘icc_profile’].

Raises:       
PyCMSError –

PIL.ImageCms.buildProofTransform(inputProfile, outputProfile, proofProfile, inMode, outMode, renderingIntent=0, proofRenderingIntent=3, flags=16384)
(pyCMS) Builds an ICC transform mapping from the inputProfile to the outputProfile, but tries to simulate the result that would be obtained on the proofProfile device.

If the input, output, or proof profiles specified are not valid filenames, a PyCMSError will be raised.

If an error occurs during creation of the transform, a PyCMSError will be raised.

If inMode or outMode are not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be raised.

This function builds and returns an ICC transform from the inputProfile to the outputProfile, but tries to simulate the result that would be obtained on the proofProfile device using renderingIntent and proofRenderingIntent to determine what to do with out-of-gamut colors. This is known as “soft-proofing”. It will ONLY work for converting images that are in inMode to images that are in outMode color format (PIL mode, i.e. “RGB”, “RGBA”, “CMYK”, etc.).

Usage of the resulting transform object is exactly the same as with ImageCms.buildTransform().

Proof profiling is generally used when using an output device to get a good idea of what the final printed/displayed image would look like on the proofProfile device when it’s quicker and easier to use the output device for judging color. Generally, this means that the output device is a monitor, or a dye-sub printer (etc.), and the simulated device is something more expensive, complicated, or time consuming (making it difficult to make a real print for color judgement purposes).

Soft-proofing basically functions by adjusting the colors on the output device to match the colors of the device being simulated. However, when the simulated device has a much wider gamut than the output device, you may obtain marginal results.

Parameters:       
inputProfile – String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object
outputProfile – String, as a valid filename path to the ICC output (monitor, usually) profile you wish to use for this transform, or a profile object
proofProfile – String, as a valid filename path to the ICC proof profile you wish to use for this transform, or a profile object
inMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
outMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
renderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for the input->proof (simulated) transform

INTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL) INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC) INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION) INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)
see the pyCMS documentation for details on rendering intents and what they do.

proofRenderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for proof->output transform

INTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL) INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC) INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION) INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)
see the pyCMS documentation for details on rendering intents and what they do.

flags – Integer (0-...) specifying additional flags
Returns:       
A CmsTransform class object.

Raises:       
PyCMSError –

PIL.ImageCms.buildProofTransformFromOpenProfiles(inputProfile, outputProfile, proofProfile, inMode, outMode, renderingIntent=0, proofRenderingIntent=3, flags=16384)
(pyCMS) Builds an ICC transform mapping from the inputProfile to the outputProfile, but tries to simulate the result that would be obtained on the proofProfile device.

If the input, output, or proof profiles specified are not valid filenames, a PyCMSError will be raised.

If an error occurs during creation of the transform, a PyCMSError will be raised.

If inMode or outMode are not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be raised.

This function builds and returns an ICC transform from the inputProfile to the outputProfile, but tries to simulate the result that would be obtained on the proofProfile device using renderingIntent and proofRenderingIntent to determine what to do with out-of-gamut colors. This is known as “soft-proofing”. It will ONLY work for converting images that are in inMode to images that are in outMode color format (PIL mode, i.e. “RGB”, “RGBA”, “CMYK”, etc.).

Usage of the resulting transform object is exactly the same as with ImageCms.buildTransform().

Proof profiling is generally used when using an output device to get a good idea of what the final printed/displayed image would look like on the proofProfile device when it’s quicker and easier to use the output device for judging color. Generally, this means that the output device is a monitor, or a dye-sub printer (etc.), and the simulated device is something more expensive, complicated, or time consuming (making it difficult to make a real print for color judgement purposes).

Soft-proofing basically functions by adjusting the colors on the output device to match the colors of the device being simulated. However, when the simulated device has a much wider gamut than the output device, you may obtain marginal results.

Parameters:       
inputProfile – String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object
outputProfile – String, as a valid filename path to the ICC output (monitor, usually) profile you wish to use for this transform, or a profile object
proofProfile – String, as a valid filename path to the ICC proof profile you wish to use for this transform, or a profile object
inMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
outMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
renderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for the input->proof (simulated) transform

INTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL) INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC) INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION) INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)
see the pyCMS documentation for details on rendering intents and what they do.

proofRenderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for proof->output transform

INTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL) INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC) INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION) INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)
see the pyCMS documentation for details on rendering intents and what they do.

flags – Integer (0-...) specifying additional flags
Returns:       
A CmsTransform class object.

Raises:       
PyCMSError –

PIL.ImageCms.buildTransform(inputProfile, outputProfile, inMode, outMode, renderingIntent=0, flags=0)
(pyCMS) Builds an ICC transform mapping from the inputProfile to the outputProfile. Use applyTransform to apply the transform to a given image.

If the input or output profiles specified are not valid filenames, a PyCMSError will be raised. If an error occurs during creation of the transform, a PyCMSError will be raised.

If inMode or outMode are not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be raised.

This function builds and returns an ICC transform from the inputProfile to the outputProfile using the renderingIntent to determine what to do with out-of-gamut colors. It will ONLY work for converting images that are in inMode to images that are in outMode color format (PIL mode, i.e. “RGB”, “RGBA”, “CMYK”, etc.).

Building the transform is a fair part of the overhead in ImageCms.profileToProfile(), so if you’re planning on converting multiple images using the same input/output settings, this can save you time. Once you have a transform object, it can be used with ImageCms.applyProfile() to convert images without the need to re-compute the lookup table for the transform.

The reason pyCMS returns a class object rather than a handle directly to the transform is that it needs to keep track of the PIL input/output modes that the transform is meant for. These attributes are stored in the “inMode” and “outMode” attributes of the object (which can be manually overridden if you really want to, but I don’t know of any time that would be of use, or would even work).

Parameters:       
inputProfile – String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object
outputProfile – String, as a valid filename path to the ICC output profile you wish to use for this transform, or a profile object
inMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
outMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
renderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for the transform

INTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL) INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC) INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION) INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)
see the pyCMS documentation for details on rendering intents and what they do.

flags – Integer (0-...) specifying additional flags
Returns:       
A CmsTransform class object.

Raises:       
PyCMSError –

PIL.ImageCms.buildTransformFromOpenProfiles(inputProfile, outputProfile, inMode, outMode, renderingIntent=0, flags=0)
(pyCMS) Builds an ICC transform mapping from the inputProfile to the outputProfile. Use applyTransform to apply the transform to a given image.

If the input or output profiles specified are not valid filenames, a PyCMSError will be raised. If an error occurs during creation of the transform, a PyCMSError will be raised.

If inMode or outMode are not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be raised.

This function builds and returns an ICC transform from the inputProfile to the outputProfile using the renderingIntent to determine what to do with out-of-gamut colors. It will ONLY work for converting images that are in inMode to images that are in outMode color format (PIL mode, i.e. “RGB”, “RGBA”, “CMYK”, etc.).

Building the transform is a fair part of the overhead in ImageCms.profileToProfile(), so if you’re planning on converting multiple images using the same input/output settings, this can save you time. Once you have a transform object, it can be used with ImageCms.applyProfile() to convert images without the need to re-compute the lookup table for the transform.

The reason pyCMS returns a class object rather than a handle directly to the transform is that it needs to keep track of the PIL input/output modes that the transform is meant for. These attributes are stored in the “inMode” and “outMode” attributes of the object (which can be manually overridden if you really want to, but I don’t know of any time that would be of use, or would even work).

Parameters:       
inputProfile – String, as a valid filename path to the ICC input profile you wish to use for this transform, or a profile object
outputProfile – String, as a valid filename path to the ICC output profile you wish to use for this transform, or a profile object
inMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
outMode – String, as a valid PIL mode that the appropriate profile also supports (i.e. “RGB”, “RGBA”, “CMYK”, etc.)
renderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for the transform

INTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL) INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC) INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION) INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)
see the pyCMS documentation for details on rendering intents and what they do.

flags – Integer (0-...) specifying additional flags
Returns:       
A CmsTransform class object.

Raises:       
PyCMSError –

PIL.ImageCms.createProfile(colorSpace, colorTemp=-1)
(pyCMS) Creates a profile.

If colorSpace not in [“LAB”, “XYZ”, “sRGB”], a PyCMSError is raised

If using LAB and colorTemp != a positive integer, a PyCMSError is raised.

If an error occurs while creating the profile, a PyCMSError is raised.

Use this function to create common profiles on-the-fly instead of having to supply a profile on disk and knowing the path to it. It returns a normal CmsProfile object that can be passed to ImageCms.buildTransformFromOpenProfiles() to create a transform to apply to images.

Parameters:       
colorSpace – String, the color space of the profile you wish to create. Currently only “LAB”, “XYZ”, and “sRGB” are supported.
colorTemp – Positive integer for the white point for the profile, in degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50 illuminant if omitted (5000k). colorTemp is ONLY applied to LAB profiles, and is ignored for XYZ and sRGB.
Returns:       
A CmsProfile class object

Raises:       
PyCMSError –

PIL.ImageCms.getDefaultIntent(profile)
(pyCMS) Gets the default intent name for the given profile.

If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.

If an error occurs while trying to obtain the default intent, a PyCMSError is raised.

Use this function to determine the default (and usually best optimized) rendering intent for this profile. Most profiles support multiple rendering intents, but are intended mostly for one type of conversion. If you wish to use a different intent than returned, use ImageCms.isIntentSupported() to verify it will work first.

Parameters:        profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile.
Returns:        Integer 0-3 specifying the default rendering intent for this profile.
INTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL) INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC) INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION) INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)
see the pyCMS documentation for details on rendering intents and what
they do.
Raises:        PyCMSError –
PIL.ImageCms.getOpenProfile(profileFilename)
(pyCMS) Opens an ICC profile file.

The PyCMSProfile object can be passed back into pyCMS for use in creating transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).

If profileFilename is not a vaild filename for an ICC profile, a PyCMSError will be raised.

Parameters:        profileFilename – String, as a valid filename path to the ICC profile you wish to open, or a file-like object.
Returns:        A CmsProfile class object.
Raises:        PyCMSError –
PIL.ImageCms.getProfileCopyright(profile)
(pyCMS) Gets the copyright for the given profile.

If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.

If an error occurs while trying to obtain the copyright tag, a PyCMSError is raised

Use this function to obtain the information stored in the profile’s copyright tag.

Parameters:        profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile.
Returns:        A string containing the internal profile information stored in an ICC tag.
Raises:        PyCMSError –
PIL.ImageCms.getProfileDescription(profile)
(pyCMS) Gets the description for the given profile.

If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.

If an error occurs while trying to obtain the description tag, a PyCMSError is raised

Use this function to obtain the information stored in the profile’s description tag.

Parameters:        profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile.
Returns:        A string containing the internal profile information stored in an ICC tag.
Raises:        PyCMSError –
PIL.ImageCms.getProfileInfo(profile)
(pyCMS) Gets the internal product information for the given profile.

If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.

If an error occurs while trying to obtain the info tag, a PyCMSError is raised

Use this function to obtain the information stored in the profile’s info tag. This often contains details about the profile, and how it was created, as supplied by the creator.

Parameters:        profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile.
Returns:        A string containing the internal profile information stored in an ICC tag.
Raises:        PyCMSError –
PIL.ImageCms.getProfileManufacturer(profile)
(pyCMS) Gets the manufacturer for the given profile.

If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.

If an error occurs while trying to obtain the manufacturer tag, a PyCMSError is raised

Use this function to obtain the information stored in the profile’s manufacturer tag.

Parameters:        profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile.
Returns:        A string containing the internal profile information stored in an ICC tag.
Raises:        PyCMSError –
PIL.ImageCms.getProfileModel(profile)
(pyCMS) Gets the model for the given profile.

If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised.

If an error occurs while trying to obtain the model tag, a PyCMSError is raised

Use this function to obtain the information stored in the profile’s model tag.

Parameters:        profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile.
Returns:        A string containing the internal profile information stored in an ICC tag.
Raises:        PyCMSError –
PIL.ImageCms.getProfileName(profile)
(pyCMS) Gets the internal product name for the given profile.

If profile isn’t a valid CmsProfile object or filename to a profile, a PyCMSError is raised If an error occurs while trying to obtain the name tag, a PyCMSError is raised.

Use this function to obtain the INTERNAL name of the profile (stored in an ICC tag in the profile itself), usually the one used when the profile was originally created. Sometimes this tag also contains additional information supplied by the creator.

Parameters:        profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile.
Returns:        A string containing the internal name of the profile as stored in an ICC tag.
Raises:        PyCMSError –
PIL.ImageCms.get_display_profile(handle=None)
(experimental) Fetches the profile for the current display device. :returns: None if the profile is not known.

PIL.ImageCms.isIntentSupported(profile, intent, direction)
(pyCMS) Checks if a given intent is supported.

Use this function to verify that you can use your desired renderingIntent with profile, and that profile can be used for the input/output/proof profile as you desire.

Some profiles are created specifically for one “direction”, can cannot be used for others. Some profiles can only be used for certain rendering intents... so it’s best to either verify this before trying to create a transform with them (using this function), or catch the potential PyCMSError that will occur if they don’t support the modes you select.

Parameters:       
profile – EITHER a valid CmsProfile object, OR a string of the filename of an ICC profile.
intent –
Integer (0-3) specifying the rendering intent you wish to use with this profile

INTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL) INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC) INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION) INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)
see the pyCMS documentation for details on rendering intents and what
they do.
direction –
Integer specifying if the profile is to be used for input, output, or proof

INPUT = 0 (or use ImageCms.DIRECTION_INPUT) OUTPUT = 1 (or use ImageCms.DIRECTION_OUTPUT) PROOF = 2 (or use ImageCms.DIRECTION_PROOF)
Returns:       
1 if the intent/direction are supported, -1 if they are not.

Raises:       
PyCMSError –

PIL.ImageCms.profileToProfile(im, inputProfile, outputProfile, renderingIntent=0, outputMode=None, inPlace=0, flags=0)
(pyCMS) Applies an ICC transformation to a given image, mapping from inputProfile to outputProfile.

If the input or output profiles specified are not valid filenames, a PyCMSError will be raised. If inPlace == TRUE and outputMode != im.mode, a PyCMSError will be raised. If an error occurs during application of the profiles, a PyCMSError will be raised. If outputMode is not a mode supported by the outputProfile (or by pyCMS), a PyCMSError will be raised.

This function applies an ICC transformation to im from inputProfile’s color space to outputProfile’s color space using the specified rendering intent to decide how to handle out-of-gamut colors.

OutputMode can be used to specify that a color mode conversion is to be done using these profiles, but the specified profiles must be able to handle that mode. I.e., if converting im from RGB to CMYK using profiles, the input profile must handle RGB data, and the output profile must handle CMYK data.

Parameters:       
im – An open PIL image object (i.e. Image.new(...) or Image.open(...), etc.)
inputProfile – String, as a valid filename path to the ICC input profile you wish to use for this image, or a profile object
outputProfile – String, as a valid filename path to the ICC output profile you wish to use for this image, or a profile object
renderingIntent –
Integer (0-3) specifying the rendering intent you wish to use for the transform

INTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL) INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC) INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION) INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)
see the pyCMS documentation for details on rendering intents and what they do.

outputMode – A valid PIL mode for the output image (i.e. “RGB”, “CMYK”, etc.). Note: if rendering the image “inPlace”, outputMode MUST be the same mode as the input, or omitted completely. If omitted, the outputMode will be the same as the mode of the input image (im.mode)
inPlace – Boolean (1 = True, None or 0 = False). If True, the original image is modified in-place, and None is returned. If False (default), a new Image object is returned with the transform applied.
flags – Integer (0-...) specifying additional flags
Returns:       
Either None or a new PIL image object, depending on value of inPlace

Raises:       
PyCMSError –

PIL.ImageCms.versions()
(pyCMS) Fetches versions.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 12:00:38 | 显示全部楼层
ImageDraw Module
The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.

For a more advanced drawing library for PIL, see the aggdraw module.

Example: Draw a gray cross over an image
from PIL import Image, ImageDraw

im = Image.open("lena.pgm")

draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)
del draw

# write to stdout
im.save(sys.stdout, "PNG")
Concepts
Coordinates
The graphics interface uses the same coordinate system as PIL itself, with (0, 0) in the upper left corner.

Colors
To specify colors, you can use numbers or tuples just as you would use with PIL.Image.Image.new() or PIL.Image.Image.putpixel(). For “1”, “L”, and “I” images, use integers. For “RGB” images, use a 3-tuple containing integer values. For “F” images, use integer or floating point values.

For palette images (mode “P”), use integers as color indexes. In 1.1.4 and later, you can also use RGB 3-tuples or color names (see below). The drawing layer will automatically assign color indexes, as long as you don’t draw with more than 256 colors.

Color Names
See Color Names for the color names supported by Pillow.

Fonts
PIL can use bitmap fonts or OpenType/TrueType fonts.

Bitmap fonts are stored in PIL’s own format, where each font typically consists of a two files, one named .pil and the other usually named .pbm. The former contains font metrics, the latter raster data.

To load a bitmap font, use the load functions in the ImageFont module.

To load a OpenType/TrueType font, use the truetype function in the ImageFont module. Note that this function depends on third-party libraries, and may not available in all PIL builds.

Example: Draw Partial Opacity Text
from PIL import Image, ImageDraw, ImageFont
# get an image
base = Image.open('Pillow/Tests/images/lena.png').convert('RGBA')

# make a blank image for the text, initialized to transparent text color
txt = Image.new('RGBA', base.size, (255,255,255,0))

# get a font
fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 40)
# get a drawing context
d = ImageDraw.Draw(txt)

# draw text, half opacity
d.text((10,10), "Hello", font=fnt, fill=(255,255,255,128))
# draw text, full opacity
d.text((10,60), "World", font=fnt, fill=(255,255,255,255))

out = Image.alpha_composite(base, txt)

out.show()
Functions
class PIL.ImageDraw.Draw(im, mode=None)
Creates an object that can be used to draw in the given image.

Note that the image will be modified in place.

Parameters:       
im – The image to draw in.
mode – Optional mode to use for color values. For RGB images, this argument can be RGB or RGBA (to blend the drawing into the image). For all other modes, this argument must be the same as the image mode. If omitted, the mode defaults to the mode of the image.
Methods
PIL.ImageDraw.Draw.arc(xy, start, end, fill=None)
Draws an arc (a portion of a circle outline) between the start and end angles, inside the given bounding box.

Parameters:       
xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].
start – Starting angle, in degrees. Angles are measured from 3 o’clock, increasing clockwise.
end – Ending angle, in degrees.
fill – Color to use for the arc.
PIL.ImageDraw.Draw.bitmap(xy, bitmap, fill=None)
Draws a bitmap (mask) at the given position, using the current fill color for the non-zero portions. The bitmap should be a valid transparency mask (mode “1”) or matte (mode “L” or “RGBA”).

This is equivalent to doing image.paste(xy, color, bitmap).

To paste pixel data into an image, use the paste() method on the image itself.

PIL.ImageDraw.Draw.chord(xy, start, end, fill=None, outline=None)
Same as arc(), but connects the end points with a straight line.

Parameters:       
xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].
outline – Color to use for the outline.
fill – Color to use for the fill.
PIL.ImageDraw.Draw.ellipse(xy, fill=None, outline=None)
Draws an ellipse inside the given bounding box.

Parameters:       
xy – Four points to define the bounding box. Sequence of either [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].
outline – Color to use for the outline.
fill – Color to use for the fill.
PIL.ImageDraw.Draw.line(xy, fill=None, width=0)
Draws a line between the coordinates in the xy list.

Parameters:       
xy – Sequence of either 2-tuples like [(x, y), (x, y), ...] or numeric values like [x, y, x, y, ...].
fill – Color to use for the line.
width –
The line width, in pixels. Note that line joins are not handled well, so wide polylines will not look good.

New in version 1.1.5.

Note

This option was broken until version 1.1.6.

PIL.ImageDraw.Draw.pieslice(xy, start, end, fill=None, outline=None)
Same as arc, but also draws straight lines between the end points and the center of the bounding box.

Parameters:       
xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].
start – Starting angle, in degrees. Angles are measured from 3 o’clock, increasing clockwise.
end – Ending angle, in degrees.
fill – Color to use for the fill.
outline – Color to use for the outline.
PIL.ImageDraw.Draw.point(xy, fill=None)
Draws points (individual pixels) at the given coordinates.

Parameters:       
xy – Sequence of either 2-tuples like [(x, y), (x, y), ...] or numeric values like [x, y, x, y, ...].
fill – Color to use for the point.
PIL.ImageDraw.Draw.polygon(xy, fill=None, outline=None)
Draws a polygon.

The polygon outline consists of straight lines between the given coordinates, plus a straight line between the last and the first coordinate.

Parameters:       
xy – Sequence of either 2-tuples like [(x, y), (x, y), ...] or numeric values like [x, y, x, y, ...].
outline – Color to use for the outline.
fill – Color to use for the fill.
PIL.ImageDraw.Draw.rectangle(xy, fill=None, outline=None)
Draws a rectangle.

Parameters:       
xy – Four points to define the bounding box. Sequence of either [(x0, y0), (x1, y1)] or [x0, y0, x1, y1]. The second point is just outside the drawn rectangle.
outline – Color to use for the outline.
fill – Color to use for the fill.
PIL.ImageDraw.Draw.shape(shape, fill=None, outline=None)
Warning

This method is experimental.

Draw a shape.

PIL.ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None)
Draws the string at the given position.

Parameters:       
xy – Top left corner of the text.
text – Text to be drawn. If it contains any newline characters, the text is passed on to mulitiline_text()
fill – Color to use for the text.
font – An ImageFont instance.
PIL.ImageDraw.Draw.multiline_text(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left")
Draws the string at the given position.

Parameters:       
xy – Top left corner of the text.
text – Text to be drawn.
fill – Color to use for the text.
font – An ImageFont instance.
spacing – The number of pixels between lines.
align – “left”, “center” or “right”.
PIL.ImageDraw.Draw.textsize(text, font=None)
Return the size of the given string, in pixels.

Parameters:       
text – Text to be measured. If it contains any newline characters, the text is passed on to mulitiline_textsize()
font – An ImageFont instance.
PIL.ImageDraw.Draw.multiline_textsize(text, font=None, spacing=0)
Return the size of the given string, in pixels.

Parameters:       
text – Text to be measured.
font – An ImageFont instance.
spacing – The number of pixels between lines.
Legacy API
The Draw class contains a constructor and a number of methods which are provided for backwards compatibility only. For this to work properly, you should either use options on the drawing primitives, or these methods. Do not mix the old and new calling conventions.

PIL.ImageDraw.ImageDraw(image)
Return type:        Draw
PIL.ImageDraw.Draw.setfont(font)
Deprecated since version 1.1.5.

Sets the default font to use for the text method.

Parameters:        font – An ImageFont instance.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 12:01:22 | 显示全部楼层
ImageEnhance Module
The ImageEnhance module contains a number of classes that can be used for image enhancement.

Example: Vary the sharpness of an image
from PIL import ImageEnhance

enhancer = ImageEnhance.Sharpness(image)

for i in range(8):
    factor = i / 4.0
    enhancer.enhance(factor).show("Sharpness %f" % factor)
Also see the enhancer.py demo program in the Scripts/ directory.

Classes
All enhancement classes implement a common interface, containing a single method:

class PIL.ImageEnhance._Enhance
enhance(factor)
Returns an enhanced image.

Parameters:        factor – A floating point value controlling the enhancement. Factor 1.0 always returns a copy of the original image, lower factors mean less color (brightness, contrast, etc), and higher values more. There are no restrictions on this value.
Return type:        Image
class PIL.ImageEnhance.Color(image)
Adjust image color balance.

This class can be used to adjust the colour balance of an image, in a manner similar to the controls on a colour TV set. An enhancement factor of 0.0 gives a black and white image. A factor of 1.0 gives the original image.

class PIL.ImageEnhance.Contrast(image)
Adjust image contrast.

This class can be used to control the contrast of an image, similar to the contrast control on a TV set. An enhancement factor of 0.0 gives a solid grey image. A factor of 1.0 gives the original image.

class PIL.ImageEnhance.Brightness(image)
Adjust image brightness.

This class can be used to control the brightness of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image.

class PIL.ImageEnhance.Sharpness(image)
Adjust image sharpness.

This class can be used to adjust the sharpness of an image. An enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 12:02:49 | 显示全部楼层
ImageFile Module
The ImageFile module provides support functions for the image open and save functions.

In addition, it provides a Parser class which can be used to decode an image piece by piece (e.g. while receiving it over a network connection). This class implements the same consumer interface as the standard sgmllib and xmllib modules.

Example: Parse an image
from PIL import ImageFile

fp = open("lena.pgm", "rb")

p = ImageFile.Parser()

while 1:
    s = fp.read(1024)
    if not s:
        break
    p.feed(s)

im = p.close()

im.save("copy.jpg")
Parser
class PIL.ImageFile.Parser
Incremental image parser. This class implements the standard feed/close consumer interface.

In Python 2.x, this is an old-style class.

close()
(Consumer) Close the stream.

Returns:        An image object.
Raises:        IOError – If the parser failed to parse the image file either because it cannot be identified or cannot be decoded.
feed(data)
(Consumer) Feed data to the parser.

Parameters:        data – A string buffer.
Raises:        IOError – If the parser failed to parse the image file.
reset()
(Consumer) Reset the parser. Note that you can only call this method immediately after you’ve created a parser; parser instances cannot be reused.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 12:03:50 | 显示全部楼层
ImageFilter Module
The ImageFilter module contains definitions for a pre-defined set of filters, which can be be used with the Image.filter() method.

Example: Filter an image
from PIL import ImageFilter

im1 = im.filter(ImageFilter.BLUR)

im2 = im.filter(ImageFilter.MinFilter(3))
im3 = im.filter(ImageFilter.MinFilter)  # same as MinFilter(3)
Filters
The current version of the library provides the following set of predefined image enhancement filters:

BLUR
CONTOUR
DETAIL
EDGE_ENHANCE
EDGE_ENHANCE_MORE
EMBOSS
FIND_EDGES
SMOOTH
SMOOTH_MORE
SHARPEN
class PIL.ImageFilter.GaussianBlur(radius=2)
Gaussian blur filter.

Parameters:        radius – Blur radius.
class PIL.ImageFilter.UnsharpMask(radius=2, percent=150, threshold=3)
Unsharp mask filter.

See Wikipedia’s entry on digital unsharp masking for an explanation of the parameters.

Parameters:       
radius – Blur Radius
percent – Unsharp strength, in percent
threshold – Threshold controls the minimum brightness change that will be sharpened
class PIL.ImageFilter.Kernel(size, kernel, scale=None, offset=0)
Create a convolution kernel. The current version only supports 3x3 and 5x5 integer and floating point kernels.

In the current version, kernels can only be applied to “L” and “RGB” images.

Parameters:       
size – Kernel size, given as (width, height). In the current version, this must be (3,3) or (5,5).
kernel – A sequence containing kernel weights.
scale – Scale factor. If given, the result for each pixel is divided by this value. the default is the sum of the kernel weights.
offset – Offset. If given, this value is added to the result, after it has been divided by the scale factor.
class PIL.ImageFilter.RankFilter(size, rank)
Create a rank filter. The rank filter sorts all pixels in a window of the given size, and returns the rank‘th value.

Parameters:       
size – The kernel size, in pixels.
rank – What pixel value to pick. Use 0 for a min filter, size * size / 2 for a median filter, size * size - 1 for a max filter, etc.
class PIL.ImageFilter.MedianFilter(size=3)
Create a median filter. Picks the median pixel value in a window with the given size.

Parameters:        size – The kernel size, in pixels.
class PIL.ImageFilter.MinFilter(size=3)
Create a min filter. Picks the lowest pixel value in a window with the given size.

Parameters:        size – The kernel size, in pixels.
class PIL.ImageFilter.MaxFilter(size=3)
Create a max filter. Picks the largest pixel value in a window with the given size.

Parameters:        size – The kernel size, in pixels.
class PIL.ImageFilter.ModeFilter(size=3)
Create a mode filter. Picks the most frequent pixel value in a box with the given size. Pixel values that occur only once or twice are ignored; if no pixel value occurs more than twice, the original pixel value is preserved.

Parameters:        size – The kernel size, in pixels.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 12:04:28 | 显示全部楼层
ImageFont Module
The ImageFont module defines a class with the same name. Instances of this class store bitmap fonts, and are used with the PIL.ImageDraw.Draw.text() method.

PIL uses its own font file format to store bitmap fonts. You can use the :command`pilfont` utility to convert BDF and PCF font descriptors (X window font formats) to this format.

Starting with version 1.1.4, PIL can be configured to support TrueType and OpenType fonts (as well as other font formats supported by the FreeType library). For earlier versions, TrueType support is only available as part of the imToolkit package

Example
from PIL import ImageFont, ImageDraw

draw = ImageDraw.Draw(image)

# use a bitmap font
font = ImageFont.load("arial.pil")

draw.text((10, 10), "hello", font=font)

# use a truetype font
font = ImageFont.truetype("arial.ttf", 15)

draw.text((10, 25), "world", font=font)
Functions
PIL.ImageFont.load(filename)
Load a font file. This function loads a font object from the given bitmap font file, and returns the corresponding font object.

Parameters:        filename – Name of font file.
Returns:        A font object.
Raises:        IOError – If the file could not be read.
PIL.ImageFont.load_path(filename)
Load font file. Same as load(), but searches for a bitmap font along the Python path.

Parameters:        filename – Name of font file.
Returns:        A font object.
Raises:        IOError – If the file could not be read.
PIL.ImageFont.truetype(font=None, size=10, index=0, encoding='')
Load a TrueType or OpenType font file, and create a font object. This function loads a font object from the given file, and creates a font object for a font of the given size.

This function requires the _imagingft service.

Parameters:       
font – A truetype font file. Under Windows, if the file is not found in this filename, the loader also looks in Windows fonts/ directory.
size – The requested size, in points.
index – Which font face to load (default is first available face).
encoding – Which font encoding to use (default is Unicode). Common encodings are “unic” (Unicode), “symb” (Microsoft Symbol), “ADOB” (Adobe Standard), “ADBE” (Adobe Expert), and “armn” (Apple Roman). See the FreeType documentation for more information.
Returns:       
A font object.

Raises:       
IOError – If the file could not be read.

PIL.ImageFont.load_default()
Load a “better than nothing” default font.

New in version 1.1.4.

Returns:        A font object.
Methods
PIL.ImageFont.ImageFont.getsize(text)
Returns:        (width, height)
PIL.ImageFont.ImageFont.getmask(text, mode='')
Create a bitmap for the text.

If the font uses antialiasing, the bitmap should have mode “L” and use a maximum value of 255. Otherwise, it should have mode “1”.

Parameters:       
text – Text to render.
mode –
Used by some graphics drivers to indicate what mode the driver prefers; if empty, the renderer may return either mode. Note that the mode is always a string, to simplify C-level implementations.

New in version 1.1.5.

Returns:       
An internal PIL storage memory instance as defined by the PIL.Image.core interface module.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-11-8 12:06:09 | 显示全部楼层
ImageGrab Module (OS X and Windows only)
The ImageGrab module can be used to copy the contents of the screen or the clipboard to a PIL image memory.

Note

The current version works on OS X and Windows only. OS X support was added in 3.0.0.
New in version 1.1.3.

PIL.ImageGrab.grab(bbox=None)
Take a snapshot of the screen. The pixels inside the bounding box are returned as an “RGB” image on Windows or “RGBA” on OS X. If the bounding box is omitted, the entire screen is copied.

New in version 1.1.3.

Parameters:        bbox – What region to copy. Default is the entire screen.
Returns:        An image
PIL.ImageGrab.grabclipboard()
Take a snapshot of the clipboard image, if any.

New in version 1.1.4.

Returns:        On Windows, an image, a list of filenames, or None if the clipboard does not contain image data or filenames. Note that if a list is returned, the filenames may not represent image files.
On Mac, this is not currently supported.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-11-8 12:25:56 | 显示全部楼层
英文太差看不懂,缩略图什么的
想知道小甲鱼最近在做啥?请访问 -> 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.
想知道小甲鱼最近在做啥?请访问 -> 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
想知道小甲鱼最近在做啥?请访问 -> 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.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

在公司开国外网站很快,先把原文下载下来,有时间我会挑重点和常用的函数做翻译
想知道小甲鱼最近在做啥?请访问 -> 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.
想知道小甲鱼最近在做啥?请访问 -> 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
想知道小甲鱼最近在做啥?请访问 -> 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
想知道小甲鱼最近在做啥?请访问 -> 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.
想知道小甲鱼最近在做啥?请访问 -> 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.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-27 02:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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