Python Pillow (PIL) library usage introduction

Python Pillow (PIL) library usage introduction

The Pillow library is a third-party library for Python.

In Python2, PIL (Python Imaging Library) is a very useful image processing library, but PIL does not support Python3, so some people (Alex Clark and Contributors) provided Pillow, which can be used in Python3.

Official document path: https://pillow.readthedocs.io/en/latest/

One, install Pillow

pip install pillow

After the Pillow library is successfully installed, PIL must be used to import the package, but not Pillow or Pillow.

import PIL
from PIL import Image

In the Pillow library, in addition to more than twenty modules, it also supports a lot of plug-ins. One of the most commonly used is the Image class of the same name in the Image module. Many other modules perform further special processing of images on the basis of the Image module. The Image module will import some parts for use. This article introduces the common methods of the Image module.

Second, open the local picture

Original image:

# coding=utf-8
from PIL import Image

image = Image.open("yazi.jpg")
image.show()

operation result:

open(fp, mode='r'): Open an image, which is a function in the Image module. If the picture and the current code are in the same directory, you can only write the file name of the picture, otherwise the path of the spliced ​​picture is required. The mode defaults to'r' and must also be'r'.

show(): Call the picture display software to open the picture. After opening, the program will be blocked and needs to be closed manually.

Three, create a new picture

from PIL import Image


image = Image.new('RGB', (160, 90), (0, 0, 255))
image.show()

operation result:

new(mode, size, color=0): Create a picture (canvas) for drawing. It is a function in the Image module. There are 3 parameters.

mode, the mode of the picture, such as "RGB" (abbreviation of the three primary colors of red, green, and blue, true color image), "L" (grayscale, black and white image), etc.

size, the size of the picture. It is a tuple of length 2 (width, height), which represents the pixel size.

color, the color of the picture, the default value is 0 means black. You can pass in a tuple of length 3 to represent the color, or you can pass in the hexadecimal number of the color. After version 1.1.4, you can also directly pass in the English words of the color, such as (0, 0, 255) can be replaced by'#0000FF' or'blue', both of which mean blue.

Fourth, the common attributes of the Image module

from PIL import Image


image = Image.open("yazi.jpg")
print('width: ', image.width)
print('height: ', image.height)
print('size: ', image.size)
print('mode: ', image.mode)
print('format: ', image.format)
print('category: ', image.category)
print('readonly: ', image.readonly)
print('info: ', image.info)

operation result:

width:  1557
height:  911
size:  (1557, 911)
mode:  RGBA
format:  PNG
category:  0
readonly:  1
info:  {'dpi': (120, 120), 'Software': 'Snipaste'}

The width attribute represents the pixel width of the image, the height attribute represents the pixel height of the image, width and height form the size attribute, and size is a tuple.

The mode attribute indicates the mode of the picture, such as RGBA, RGB, P, L, etc.

The format attribute indicates the format of the picture, and the format is generally related to the suffix extension of the picture. The category attribute indicates the category of the image.

The readonly attribute indicates whether the image is read-only, and the value is 1 or 0, which indicates a Boolean value.

The info attribute represents the information of the picture and is a dictionary.

Five, picture mode and mode conversion

1. Picture mode

There are many modes for pictures, and the following standard modes are supported, please refer to: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes

mode description
1 1-bit pixel, black and white, each byte stores one pixel
L 8-bit pixels, black and white
P  8-bit pixels, use palette to map to any other mode
RGB  3x8 bit pixels, true color
RGBA  4x8 bit pixels, true color with transparent mask
CMYK  4x8 bit pixels, color separation
YCbCr  3x8 bit pixels, color video format
LAB  3x8 bit pixels, L * a * b color space
HSV  3x8 bit pixels, hue, saturation, value color space
I  32-bit signed integer pixel
F  32-bit floating point pixels

The range of 1-bit pixels is 0-1, 0 means black, 1 means white, and the middle means gray. The range of 8-bit pixels is 0-255, such as RGB (0, 0, 0) means black, (255, 255, 255) means white, and so on.

2. Picture mode conversion

from PIL import Image


image = Image.open("yazi.jpg")
print(image.mode)
image1 = image.convert('1')
print(image1.mode)
# image1.show()
image_l = image.convert('L')
print(image_l.mode)
# image_l.show()
image_p = image.convert('P')
print(image_p.mode)
image_p.show()

operation result:

RGBA
1
L
P

convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256): Convert the picture to the specified mode and return a copy of the converted picture. If you do not specify a mode, a mode that preserves all the information of the picture and does not use the palette is automatically selected (the usual result is no conversion). When converting a color image to grayscale ('L'), use ITU-R 601-2 for brightness conversion: L = R * 299/1000 + G * 587/1000 + B * 114/1000. When converting grayscale ('L') or true color ('RGB') to mode '1', if the dither parameter is'NONE', all values ​​greater than 128 are set to 255 (white), and all other values ​​are set It is 0 (black).

The convert() method has 5 parameters.

mode, the mode of the picture, pass in the mode that needs to be converted. Some modes do not support conversion, and the code will report an error.

matrix, the conversion matrix. When passing in this parameter, you should pass in a tuple composed of floating-point numbers, the length of the tuple is 4 or 12. Matrix only supports conversion from a few modes to'L' or'RGB'.

dither, high frequency vibration, used to control color dithering. Used when converting from mode'RGB' to'P' or from'RGB' or'L' to '1'. The available methods are'NONE' or'FLOYDSTEINBERG' (default). This function is not used when the matrix parameter is provided.

palette, palette, used to control the generation of palette. It is used when converting from the mode'RGB' to'P'. The available methods are'WEB' (default) or'ADAPTIVE'. 'ADAPTIVE' means to use an adaptive color palette.

colors, the number of colors used by the adaptive palette. When the palette parameter is'ADAPTIVE', it is used to control the number of colors in the palette. The default is the maximum value, which is 256 colors.

2.1 Comparison of the effect of matrix parameters

from PIL import Image


image = Image.open("yazi.jpg")
image_rgb = image.convert('RGB')
print(image_rgb.mode)
image_l = image_rgb.convert('L')
image_l.show()
matrix = (0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6)
image_l2 = image_rgb.convert('L', matrix=matrix)
image_l2.show()

operation result:

In the above code, a tuple of length 12 is passed to the matrix parameter. The value of the matrix changes the effect of the conversion. The degree of change depends on the value of the floating-point number in the passed tuple. Note that some modes are not supported, such as'RGBA', and the length of the incoming tuple must be 4 or 12, otherwise an error will be reported.

2.2 Effect comparison of palette parameters

from PIL import Image


image = Image.open("yazi.jpg")
image_p = image.convert('P')
# image_l.show()
image_p2 = image.convert('P', palette='ADAPTIVE', colors=256)
image_p2.show()

operation result:

In the above code, the palette parameter is changed to'ADAPTIVE', the picture difference is not big, but if the colors are made smaller, the difference will be larger, but that will make the picture effect worse.

6. Copy, paste and save pictures

from PIL import Image


image = Image.open("yazi.jpg")
image_copy = image.copy()
# image_copy.show()
image_new = Image.new('RGB', (160, 90), (0, 0, 255))
image_new2 = Image.new('L', (160, 90), '#646464')
image_copy.paste(image_new, (100, 100, 260, 190), mask=image_new2)
image_copy.save('duck.png')
image_save = Image.open('duck.png')
print(image_save.format, image_save.mode)
image_copy.show()

operation result:

PNG RGBA

copy(): Copy the current picture, the copied picture is exactly the same as the original picture. If you want to paste some content on the picture, but also want to keep the original picture, you can use this method.

paste(im, box=None, mask=None): Paste another picture into the current picture. If the pasted pattern does not match, the pattern of the pasted picture will be converted to the pattern of the current picture. There are 3 parameters.

im, the picture to be pasted. Pass in an image. When the second parameter box specifies an area, the im parameter can also be an integer or a color value (tuple representation, hexadecimal representation and color name can be used, such as image_new in the code above It can be replaced by (0, 0, 255),'#0000FF','blue').

box, the location or area where the picture is pasted. Pass in a tuple with a length of 2 or 4. If no value is passed, the default is (0, 0), and the picture is pasted in the upper left corner of the current picture. If a tuple (x, y) of length 2 is passed in, it indicates the coordinate position of the upper left corner of the pasted image. If a tuple of length 4 (x0, y0, x1, y1) is passed in, it indicates the area where the picture is pasted. At this time, the size of the area must be consistent with the picture being pasted, otherwise an error will be reported, and the tuple length passed in is another value Errors will also be reported.

mask, mask. Pass in a picture with the same size as the pasted picture, and an image with the mode of '1','L' or'RGBA' can be used. If the color value of the mask image is 255, it will be pasted directly according to the color of the pasted picture. If the color value of the mask image is 0, the color of the current picture is retained (equivalent to no pasting), if the color value of the mask image is 0~ For values ​​between 255, mix im and mask before pasting.

save(fp, format=None, **params): Save the current picture under the specified file name, and after running, the picture will be saved under the current path under the new name (you can also specify the path). The file name is best to have an extension, which is convenient to open. Format indicates the format of the picture. If format is not specified, it will be parsed according to the extension (if it can be parsed). Generally, there is no need to specify format. Pass in a file name with an extension. can.

Seven, picture cropping and zooming

from PIL import Image


image = Image.open("yazi.jpg")
image_crop = image.crop(box=(300, 300, 800, 700))
# image_crop.show()
print('before resize: ', image.size)
image_resize = image.resize((500, 400), resample=Image.LANCZOS, box=(100, 100, 1200, 800), reducing_gap=5.0)
print('after resize: ', image_resize.size)
image_resize.show()

operation result:

before resize:  (1557, 911)
after resize:  (500, 400)

crop(box=None): Crop the picture and return the picture in the cropped area. The box represents the cropped area. Pass in a tuple of length 4 (x0, y0, x1, y1). If you don’t pass it, the default is to copy the original image, which is equivalent to the copy() method. If the cropped area exceeds the area of ​​the original image, The excess part is filled with pixel grids.

resize(size, resample=BICUBIC, box=None, reducing_gap=None): Resize the picture and return a copy of the zoomed picture. There are 4 parameters.

size, the size of the image after zooming, and a tuple of length 2 (width, height) is passed in.

resample, resampling, is an optional resampling filter. You can pass in Image.NEAREST, Image.BOX, Image.BILINEAR, Image.HAMMING, Image.BICUBIC, Image.LANCZOS. The default is Image.BICUBIC. If the mode of the image is '1' or'P', it is always set to Image.NEAREST.

box, zoom the area of ​​the picture. Pass in a tuple (x0, y0, x1, y1) with a length of 4. This area must be within the (0, 0, width, height) range of the original image. If it exceeds the range, an error will be reported. If the value is not passed, the default will be integer The original image is zoomed.

reducing_gap, reduce the gap. Pass in a floating point number to optimize the image zooming effect. By default, no optimization is performed. When the value is greater than 3.0, the optimization effect is basically fair resampling.

The Image module also has many methods and functions for image processing. For more information, please refer to: https://blog.csdn.net/weixin_43790276/article/details/108673454

 

 

Guess you like

Origin blog.csdn.net/weixin_43790276/article/details/108478270