Introduction to the main functions and usage of the pillow library
Overview:
Pillow is a very commonly used Python image processing library, which is the Python Imaging Library (PIL ), providing rich image processing functions. Pillow supports reading and writing of various image formats, basic image processing operations, image conversion, image enhancement, image synthesis and other functions. This article will introduce each main function of the Pillow library and provide specific code examples.
Install Pillow library:
Before using Pillow, you need to install it first. You can use the pip command to install the Pillow library:
pip install pillow
Open, save and display images:
Pillow can easily open, save and display images. Here are some commonly used functions and code examples:
from PIL import Image # 打开一张图像 img = Image.open('image.jpg') # 显示图像 img.show() # 保存图像 img.save('new_image.jpg')
Image resizing:
Pillow can resize images according to the specified dimensions. The following is a sample code:
from PIL import Image # 打开一张图像 img = Image.open('image.jpg') # 调整图像的尺寸 new_size = (800, 600) # 新的尺寸为800x600 resized_img = img.resize(new_size) # 显示调整后的图像 resized_img.show()
Cut and rotate images:
Pillow can cut and rotate images. The following is a sample code:
from PIL import Image # 打开一张图像 img = Image.open('image.jpg') # 剪切图像的一个区域 box = (100, 100, 500, 400) # 剪切区域的左上角和右下角的坐标 cropped_img = img.crop(box) # 旋转图像 rotated_img = img.rotate(90) # 逆时针旋转90度 # 显示剪切后的图像和旋转后的图像 cropped_img.show() rotated_img.show()
Color conversion of images:
Pillow supports converting images to different color modes. The following is a sample code:
from PIL import Image # 打开一张图像 img = Image.open('image.jpg') # 将图像转换为黑白模式 bw_img = img.convert('L') # 显示黑白图像 bw_img.show()
Image enhancement:
Pillow provides some image enhancement methods that can improve the quality of the image. The following is a sample code:
from PIL import ImageEnhance # 打开一张图像 img = Image.open('image.jpg') # 增强图像的亮度 enhancer = ImageEnhance.Brightness(img) bright_img = enhancer.enhance(1.2) # 增强亮度1.2倍 # 显示增强后的图像 bright_img.show()
Image synthesis:
Pillow can combine multiple images into one. The following is a sample code:
from PIL import Image # 打开两张图像 img1 = Image.open('image1.jpg') img2 = Image.open('image2.jpg') # 将两张图像合成 merged_img = Image.blend(img1, img2, 0.5) # 按比例合成 # 显示合成后的图像 merged_img.show()
The above is just an introduction and usage of some of the main functions provided by the Pillow library. There are many other powerful functions not mentioned in this article. By learning and using the Pillow library, we can more easily perform image processing and handle various image-related tasks.
The above is the detailed content of Introduce and use the main functions of the Pillow library. For more information, please follow other related articles on the PHP Chinese website!