Image module of PIL

from PIL import Image

The Image module provides a class with the same name to represent a PIL image.
The module also provides many functions, including the functions of loading images from files and creating new images.

Attributes

format

im.format ⇒ string or None

The file format of the source file, such as:'png'. For images created by the library itself, this property is set to None.

mode

im.mode ⇒ string (output string)

Image mode. This is a string that specifies the pixel format used by the image. Typical values ​​are "1", "L", "RGB" or "CMYK".
1 (1-bit pixels, black and white, stored with one pixel per byte) Binary image
L (8-bit pixels, black and white) Gray image
P (8-bit pixels, mapped to any other mode using a colour palette) index image
RGB (3x8-bit pixels, true colour) true color image
RGBA (4x8-bit pixels, true colour with transparency mask) transparent blending true color image
CMYK (4x8-bit pixels, colour separation) color separation model
YCbCr (3x8-bit pixels, colour video format)
I (32-bit signed integer pixels)
F (32-bit floating point pixels) F (32-bit floating point pixels)

size

im.size ⇒ (width, height)
PIL.Image.size
PIL.Image.width
PIL.Image.height

Image size, returns a 2-tuple (width, height).

palette

im.palette ⇒ palette or None

If there is a palette table, the mode is "P", which should be an instance of the ImagePalette class. Otherwise, it should be set to None.

info

im.info ⇒ dictionary

Returns a dictionary of image-related data. Used to transfer various non-image information read from the file.
Most methods ignore the dictionary when returning a new image; since the information is not standardized, it is impossible for the method to know whether the operation will affect the dictionary. If you need this information later, you can keep a reference to the info dictionary returned from the open method.

function

new

Image.new(mode, size) ⇒ image
Image.new(mode, size, color) ⇒ image

new : Create a new image with a given mode and size.
The size is given in the form of a (width, height) tuple in pixels. For single-band images, color is a value; for multi-band images, color is a tuple (one value for each band)

from PIL import Image
im = Image.new("RGB", (512, 512), "white")
# 颜色表示:“#ff0000”, “rgb(255,0,0)”,“rgb(100%,0%,0%)”,“hsl(0,100%,50%)” ,“red”

open

Image.open(file) ⇒ image
Image.open(file, mode) ⇒ image

open : Open and identify the given image file. It is a lazy operation; this function reads the file header and calls the load method to force the actual image data to be loaded until it tries to process the data.
mode ='r', you can use character string (representing file name) or file object as file parameter. In the latter case, the file object must implement the read, seek, and tell methods and be opened in binary mode.

from PIL import Image
im = Image.open("lenna.jpg")

blend

Image.blend(image1, image2, alpha) ⇒ image

Blending : out = image1 * (1.0-alpha) + image2 * alpha
By interpolating image2 between the given images image1, the constant alpha is used to control the proportion to generate a new image. The two images must have the same size and the same mode.

composite

Image.composite(image1, image2, mask) ⇒ image

Synthesis : Create a new image by inserting between the given images, using the corresponding pixel in the mask image as the alpha value.
The mask mode has "1", "L" or "RGBA", and all parameter images must be the same size.

eval

Image.eval(image, function) ⇒ image

Use this function for each pixel of a given image, and if the image has multiple bands, apply it to each band.
Note that for each possible pixel value, it is calculated once, so random components or other generators cannot be used.
eval() is a function in a programming language. Its function is to get the return value . Different languages ​​have similarities.

frombuffer

Image.frombuffer(mode, size, data) ⇒ image

raw decoder : Use a standard "original code" decoder to create image memory from the pixel data in a string or buffer object. For some modes, the image memory will share memory with the original buffer (this means that changes to the original buffer object will be reflected in the image). Not all modes can share memory; supported modes include "L", "RGBX", "RGBA" and "CMYK". For other modes, the behavior of this function is similar to the corresponding call to the fromstring function.

im = Image.frombuffer(mode, size, data, "raw", mode, 0, 1)

fromstring

Image.fromstring(mode, size, data) ⇒ image

Source data image : Use a standard " source code" decoder to create an image from the pixel data in the string.

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

Image.fromstring("RGB",(10,10),datas.tostring()).save("./data/1.png","png")

Same as above, but allows you to use pixel decoders supported by PIL. Note that only the pixel data is decoded, not the entire image file. If there is a complete image file in the string, wrap it in a StringIO object and load it with open.

merge

Image.merge(mode, bands) ⇒ image

Fusion : Create a new image from multiple single-band images. Bands are given in the form of tuples or image lists, and each band is described by a pattern. All bands must have the same size.

method

Instances of the Image class have the following methods. Unless otherwise stated, all methods return a new instance of the Image class and save the resulting image.

convert

im.convert(mode) ⇒ image

Mode conversion : Convert the image to another mode and return to the new image.

copy

im.copy() ⇒ image

Copy the image. Paste the original image content into the image, and still retain the original content, use this method.

crop

im.crop(box) ⇒ image

Crop : Return a copy of the rectangular area from the current image. The box is a 4-tuple that defines the coordinates of the left, top, right, and bottom pixels. This is a lazy operation. Changes to the source image may or may not be reflected in the cropped image. To obtain a single copy, call the load method (invisible) on the cropped copy.

close

Image.close()

Close the file pointer.
This operation will destroy the image core and release its memory. The image data will be unavailable afterwards. This function is only used to close the image that has not been read by the load() method and close its file.

draft

im.draft(mode, size)

Configure the image file loader : make it return the image version as close as possible to the given mode and size.
For example, you can use this method to convert a color JPEG to grayscale when loading, or to extract a 128x192 version from a PCD file. Note that this method reconfigures the file reader. If the image is already loaded, this method has no effect.

filter

im.filter(filter) ⇒ image

Returns the filtered image. See The ImageFilter Module

fromstring

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

String data load: load data into the current image. im determines basic information such as mode and size, and only needs to load specific pixel values.

getbands

im.getbands() ⇒ tuple of strings

Return a tuple containing the name of each band. For example, getband on the RGB image returns ("R", "G", "B").

getbbox

im.getbbox() ⇒ 4-tuple or None

Calculate the square boundary of the non-zero area of ​​the image. This bounding box is a 4-tuple that defines the left, top, right, and bottom pixel coordinates. If the image is empty, this method will return empty. Note that the function Double B .

from PIL import Image
im = Image.open("./data/lena.png")
im.getbbox()
# 输出PNG (0, 0, 512, 512)

getcolors

im.getcolors() ⇒ a list of (count, color) tuples or None
im.getcolors(maxcolors) ⇒ a list of (count, color) tuples or None

Count the color and the number of times : each element of the returned unordered list is a (count, color) tuple, where count is the number of times the corresponding color appears in the image. maxcilors: The maximum number of colors. The maximum number of colors that a multi-channel color image can have is equal to the number of pixels it contains. For example, a 50*60px picture has up to 3000 colors. If it is a grayscale image L, then maxcolors=256, single channel. (Otherwise, it is likely to return None)

img = Image.open(imgDress) 
print("src:",img.getcolors(img.size[0]*img.size[1]))
# 显示结果(1, (196, 163, 178)), (1, (193, 163, 162)), (2, (192, 163, 162)), (2, (188, 163, 162)),...

getdata

im.getdata() ⇒ sequence

Image pixel value sequence : Returns the content of this image in the form of a sequence object containing pixel values. Sequence objects are tiled, so the value in the first row immediately follows the value in the 0th row, and so on.
Note: The sequence object returned by this method is an internal PIL data type , which only supports certain sequence operations. To convert it to a normal sequence (such as printing), use list(im.getdata()).
Parameters: Band, which indicates which band to return. The default is to return all bands. To return a single frequency band, pass in the index value (for example, get the "R" band from the "RGB" image).
Returns: a sequence-like object.

img = Image.open(imgDress) 
print("src:",img.getdata())
# 显示结果[(226, 134, 118), (225, 132, 112), (222, 128, 107), (225, 132, 110), ...]

textured

im.getextrema () ⇒ 2-tuple

Get the minimum and maximum pixel values ​​of each band in the image.
Return: For a single-band image, a two-tuple containing the minimum and maximum pixel values. For multi-band images, each band contains a tuple of two tuples. Such as RGB graph, return ((72, 255), (0, 232), (47, 211)), and the minimum and maximum values ​​of each band form a tuple to form the return value.

getpalette

Image.getpalette()

Palette list : Return the image palette as a list.
Returns: a list of color values ​​[r, g, b,...], if the image does not have a palette, it is None.

getpixel

im.getpixel(xy) ⇒ value or tuple

Returns the pixel value at the given position. Parameters: xy-coordinate, expressed as (x, y). Returns: the pixel value. If the image is a multi-layer image, this method returns a tuple.

histogram

im.histogram() ⇒ list
im.histogram(mask) ⇒ list

List of pixel counts : Returns the histogram of the image. The histogram is returned as a list of pixel counts, with each pixel value corresponding to a source image. If the image has multiple bands, connect the histograms of all bands (for example, the histogram of an "RGB" image contains 768 values). (256*3=768)
This method processes dual-level images (mode "1") into grayscale ("L") images.
If a mask is provided, this method will return a histogram of the non-zero portion of the mask image in the image. The mask image must have the same size as the image, and be a two-layer image (mode "1") or a grayscale image ("L").
Parameters: mask-an optional mask.
Returns: a list containing pixel counts. The count list of each gray level, like: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 8, 6, 10, 9, 20, 37, 32, 41, 53, 74, 103, 132, 179, 193, 242, 238, 336, 386, 404, 483, 607, 628, …]

load

im.load()

Allocate storage space for the image and load it from a file (or from a source file for lazy operations). Under normal circumstances, there is no need to call this method, because the image class will automatically load it when the opened image is accessed for the first time.

pix = im.load()
print pix[x, y]
pix[x, y] = value

offset

im.offset(xoffset, yoffset) ⇒ image

Offset image : return the image offset image. Data surrounds the edge. If yoffset is omitted, it is assumed to be equal to xoffset. (Deprecated)

paste

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

Paste another image into this image. The box parameter is either a 2-tuple giving the upper left corner, or a 4-tuple defining the coordinates of the left, upper, right and lower pixels, or it is not given (same as (0,0)). If a 4-tuple is given, the size of the pasted image must match the size of the area.
If the patterns do not match, the pasted image is converted to the pattern of this image. If a mask is given, this method only updates the area indicated by the mask.

point

im.point(table) ⇒ image
im.point(function) ⇒ image
im.point(table, mode) ⇒ image
im.point(function, mode) ⇒ image

Return the Image object through a lookup table or function.

putalpha

im.putalpha (band)

Add or replace the alpha layer in this image. If the image does not have an alpha layer, it will be converted to "LA" or "RGBA". The new layer must be "L" or "1".
Parameters: alpha-the new alpha layer. This can be an "L" or "1" image with the same size as this image, or it can be an integer or other color value.

putdata

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

Copy the pixel data to this image. This method copies the data in the sequence object to the image, starting from the upper left corner (0,0) and continuing to the end of the image or sequence. The scale and offset values ​​are used to adjust the sequence value: pixel = value*scale + offset.
Parameters:
data: a sequence object.
scale: The scale value, the default is 1.0.
offset: An optional offset value. The default value is 0.0.

putpalette

im.putpalette(sequence)

Attach Palette : Attach 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 ​​represents the red, green, and blue values ​​of the corresponding pixel index. You can use an 8-bit string instead of a sequence of integers.
Parameters: datasequence, palette sequence (list or string).

putpixel

im.putpixel(xy, colour)

Modify the pixel at the given position. For single-band images, the color is a single value; for multi-band images, the color is a tuple.
Note that this method is relatively slow. For more extensive changes, paste() or ImageDraw modules can be used.

quantize

Image.quantize(colors=256, method=None, kmeans=0, palette=None) ⇒ image

Convert the image to "P" mode with the specified number of colors. For details, please refer to: Image.quantize()
Parameters: colors—the number of colors needed, <= 256

resize

Returns a resized copy of this image.

im.resize(size) ⇒ image
im.resize(size, filter) ⇒ image
Image.resize(size, resample=0)

Parameters:
size – the required size (width, height).
resample – The filters used for resampling are: PIL.Image.NEAREST, PIL.Image.BOX, PIL.Image.BILINEAR, PIL.Image.HAMMING, PIL.Image .BICUBIC or PIL.Image.LANCZOS. If omitted, or the image mode is "1" or "P", set to PIL.Image.NEAREST

rotate

im.rotate(angle) ⇒ image
im.rotate(angle, filter=NEAREST, expand=0) ⇒ image
Image.rotate(angle, resample=0, expand=0, center=None, translate=None)

Returns a rotated copy of this image. This method returns a copy of this image and rotates the given angle counterclockwise along its center.

save

im.save(outfile, options…)
im.save(outfile, format, options…)
Image.save(fp, format=None, **params)

Save this image under the given file name. If no format is specified, try to determine the format to be used from the file name extension as much as possible.

seek

im.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.

show

Show this picture. This method is mainly used for debugging.

Image.show(title=None, command=None)
Parameters:
title – Optional title to use for the image window, where possible.
command – command used to show the image

split

im.split() ⇒ sequence

Split this image into separate bands. This method returns a tuple of a single image band from the image. For example, splitting an "RGB" image creates three new images, each of which contains a copy of the original band (red, green, and blue). Returns: a tuple containing bands.

tell

im.tell() ⇒ integer

Returns the current frame number.

thumbnail

im.thumbnail(size)
im.thumbnail(size, filter)
Image.thumbnail(size, resample=3)

Thumbnail : Turn the image into a thumbnail. This method modifies the image itself to include a thumbnail version of itself, and the thumbnail is not larger than the given size.
This method calculates the appropriate thumbnail size to preserve the appearance of the image, calls the draft() method to configure the file reader (if applicable), and finally adjusts the size of the image.
Note that this function modifies the image object. If you also need to use the full resolution original image, save a copy of the original image before applying this method.

tostring

im.tostring() ⇒ string
im.tostring(encoder, parameters) ⇒ string

Use a standard "raw" encoder to return a string containing pixel data.

transform

im.transform(size, method, data) ⇒ image
im.transform(size, method, data, filter) ⇒ image
im.transform(size, EXTENT, data) ⇒ image
im.transform(size, EXTENT, data, filter) ⇒ image
im.transform(size, AFFINE, data) ⇒ image
im.transform(size, AFFINE, data, filter) ⇒ image
im.transform(size, QUAD, data) ⇒ image
im.transform(size, QUAD, data, filter) ⇒ image
im.transform(size, MESH, data) image ⇒ image
im.transform(size, MESH, data, filter) image ⇒ image
im.transform(size, PERSPECTIVE, data) image ⇒ image
im.transform(size, PERSPECTIVE, data, filter) image ⇒ image

Image transformation. This method creates a new image with a given size and the same as the original pattern, and uses the given method to copy the data to the new image.

transpose

im.transpose(method) ⇒ image

Image transpose (flip or rotate 90 degrees)

verify

im.verify()

Verify the content of the file. For data read from a file, this method attempts to determine whether the file is corrupted, without actually decoding the image data. If this method finds any problems, it will raise the appropriate exception. If you need to load an image after using this method, you must reopen the image file.

Guess you like

Origin blog.csdn.net/beauthy/article/details/105149855