Pillow image processing module

Pillow is a third-party library for Python. There is a standard library called PIL (Python Imaging Library) in Python2, but it does not support Python3, so some volunteers created Pillow based on PIL to support Python3. Pillow supports dynamic image editing.

Install Pillow

pip install pillow

After Pillow is installed successfully, you need to import it with PIL:

import PIL

from PIL import Image

Image is the most commonly used module.

Open or create a new picture

import PIL
from PIL import Image
pic = Image.open('11.jpg')
pic.show()
im = Image.new('RGB', (480, 640), ('pink'))
im.show()

The Image.new() method has three parameters: image mode (RGB), image size (width, height), color (red, green, blue). The color can directly use #0000FF or blue to represent blue.

The Image.show() method can call the system's own image viewing program to display the current image. If the corresponding program is not installed in the system, nothing will be displayed when the program is executed.

Common properties of the Image module

print('宽:', pic.width)  # 宽: 1361
print('高:', pic.height)  # 高: 1814
print('尺寸:', pic.size)  # 尺寸: (1361, 1814)
print('色彩模式:', pic.mode)  # 色彩模式: RGB
print('图像格式:', pic.format)  # 图像格式: JPEG
# print('图片类别:', pic.category)
print('只读:', pic.readonly)  # 只读: 1
print('图片信息:', pic.info)  # 图片信息: {'jfif': 257, 'jfif_version': (1, 1), 'jfif_unit': 0, 'jfif_density': (1, 1)}

The size attribute returns a tuple.

The Image.convert() method performs image mode (mode) conversion and supports the following standard modes.

convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256): Convert the current image to the specified mode and return the converted image.

If no mode is specified, a mode is selected that preserves all information about the image and does not use a palette (the usual result is no conversion).

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

The range of 1-bit pixel 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) represents black, (255, 255, 255) represents white, and so on.

pic1 = pic.convert('1')
pic1.show()

The convert() method has 5 parameters, all of which have default values. The value is passed according to the conversion mode:

mode , the mode of the image, pass in the mode that needs to be converted. Conversion between some modes is not supported, and the code will report an error.

matrix , transformation matrix. When passing in this parameter, you should pass in a tuple consisting of floating point numbers with a tuple length of 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'. Available methods are 'NONE' or 'FLOYDSTEINBERG' (default). This function is not used when the matrix argument is provided.

palette , palette, used to control the generation of palettes. Used when converting from mode 'RGB' to 'P', available methods are 'WEB' (default) or 'ADAPTIVE'. 'ADAPTIVE' means to use an adaptive 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.

Copy, paste and save images

pic = Image.open('11.jpg')
im = Image.new('RGB', (128, 128), (255, 0, 0))
im1 = Image.new('RGBA', (128, 128), (0, 0, 255))
pic1 = pic.copy()
pic1.paste(im, (640, 600), mask=im1)
pic1.save('22.jpg', quality=95, subsampling=0)

Image.copy() method : Copy and return the specified object.

Image.paste(im, (row, column), mask=None) : Based on the current image object, paste the im object to the specified position, and the mask parameter specifies the mask.

Image.save() method : Save the current image object to the specified location.

Specific instructions:

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 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 being pasted. Pass in an image. When the second parameter box specifies an area, the im parameter can also be an integer or color value (tuple representation, hexadecimal representation and color name are all acceptable, such as image_new in the above code Can be replaced by (0, 0, 255), '#0000FF', 'blue').

box , the location or area where the image 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) with a length of 2 is passed in, it represents the coordinate position of the upper left corner of the pasted image. If a tuple (x1, y1, x2, y2) with a length of 4 is passed in, it represents the area where the picture is pasted. At this time, the size of the area must be consistent with the pasted picture, otherwise an error will be reported, and the length of the passed-in tuple is other values. An error will also be reported.

mask, mask . Pass in an image with the same dimensions as the pasted image. You can use an image with mode '1', 'L' or 'RGBA'. If the color value of the mask image is 255, paste 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~ If the value is between 255, mix im and mask before pasting.

save(fp, format=None, quality=95, subsampling=0): Save the current picture with the specified file name. After running, the picture will be saved with a new name under the current path (the path can also be specified). It is best to have an extension in the file name for easy opening. format indicates the format of the image. If the format is not specified, it will be parsed according to the extension (if it can be parsed). Generally, there is no need to specify the format, just pass in a standard file name.
quality : compression ratio, default is 75.
subsampling : Optional parameters are 0, 1, 2; select 0 to achieve the requirement of small to large.

Image cropping and scaling

pic = Image.open('11.jpg')
im_crop = pic.crop(box=(200, 200, 680, 840))
im_crop.show()
im_resize = pic.resize((480, 640),reducing_gap=2)
im_resize.show()

im_crop = pic.crop(box=(200, 200, 680, 840)) : Crop the picture. The four numbers in the box parameter are the picture coordinates, which are x1, y1, x2, y2.

im_resize = pic.resize((480, 640),reducing_gap=2):

crop(box=None) : Crop the image and return the image in the cropped area. Box represents the cropped area. Pass in a tuple (x1, y1, x2, y2) with a length of 4. If not passed, 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 area is filled with pixels.

resize(size, resample=BICUBIC, box=None, reducing_gap=None) : Scale the image and return the scaled image. There are 4 parameters.

size , the size of the image after scaling, passing in a tuple of length 2 (width, height).

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

box , the area of ​​the zoomed image. Pass in a tuple of length 4 (x1, y1, x2, y2). This area must be within the range of (0, 0, width, height) of the original image. If it exceeds the range, an error will be reported. If no value is passed, the whole area will be used by default. The original image is zoomed.

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

Image rotation and flipping

  • rotate() method : Rotate the image object to any angle clockwise or counterclockwise.
  • transpose() method : Rotate or flip the picture object 90 degrees clockwise or counterclockwise. Different from the above method, it cannot be at any angle, but it can be flipped vertically or horizontally.
    ★★★★★This method is more commonly used, but according to the system prompts, the current method will be deactivated after the Pillow10 (2023-07-01) update.
im_resize.rotate(45).show()         # 图片向左(逆时针)旋转45度并显示。
im_resize.transpose(Image.FLIP_LEFT_RIGHT).show()   # 逆时针旋转90度并显示。
im_resize.transpose(Image.FLIP_TOP_BOTTOM).show()   # 逆时针旋转90度并显示。
im_resize.transpose(Image.ROTATE_90).show()     # 逆时针旋转90度并显示。
im_resize.transpose(Image.ROTATE_180).show()    # 逆时针旋转90度并显示。
im_resize.transpose(Image.ROTATE_270).show()    # 逆时针旋转90度并显示。

Picture special effects

Pillow provides some simple image effects, which require importing the ImageFilter module from the PIL library.

 pic = Image.open('11.jpg')
 def pic_filter(imfile, x):
     filters = [
         ImageFilter.BLUR,   # 模糊效果
         ImageFilter.DETAIL, # 细节效果
         ImageFilter.CONTOUR,    # 轮廓效果
         ImageFilter.EDGE_ENHANCE,   # 边缘增强(比锐化更好)
         ImageFilter.EDGE_ENHANCE_MORE,  # 进一步边缘增强
         ImageFilter.FIND_EDGES, # 查找边缘
         ImageFilter.EMBOSS,     # 浮雕效果
         ImageFilter.SHARPEN,    # 锐化
         ImageFilter.SMOOTH,     # 平滑
         ImageFilter.SMOOTH_MORE,    # 进一步平滑
     ]
 return imfile.filter(filters[x]) # 根据列表序号选择效果并显示
 pic_filter(pic,3).show()

Picture sharing

Insert image description here

Guess you like

Origin blog.csdn.net/Jo_Francis/article/details/125140121