Table of Contents
Usage of PIL library
1. Overview of PIL library
2. PIL library Image class analysis
3.图像的过滤和增强
Home Backend Development Python Tutorial Python image processing PIL library

Python image processing PIL library

Jun 23, 2022 pm 12:22 PM
python

This article brings you relevant knowledge about python, which mainly organizes related issues of the PIL library. The PIL library is a third-party library with powerful image processing capabilities. It not only includes Rich pixel and color operation functions can also be used for image archiving and batch processing. Let’s take a look at it. I hope it will be helpful to everyone.

Python image processing PIL library

Recommended learning: python

Usage of PIL library

Key points: PIL The library is a third-party library with powerful image processing capabilities. It not only contains rich pixel and color operation functions, but can also be used for image archiving and batch processing.

1. Overview of PIL library

The PIL (Python Image Library) library is a third-party library of the Python language and needs to be installed through the pip tool. The method of installing the PIL library is as follows. It should be noted that the name of the installation library is pillow.

:\>pip install pillow #或者 pip3 install pillow
Copy after login

The PIL library supports image storage, display and processing. It can handle almost all image formats and can complete operations such as scaling, cropping, overlaying, and adding lines, images, and text to images.
The PIL library can mainly meet the kinetic energy needs of image archiving and image processing.
(1) Image archiving: batch processing of images, generating image previews, image format conversion, etc.
(2) Image processing: basic image processing, pixel processing, color processing, etc.
Depending on the functions, the PIL library includes a total of 21 image-related classes. These classes can be regarded as sub-libraries
or modules in the PIL library. The sub-library list is as follows.
Image, ImageChops, ImageColor, ImageCrackCode, ImageDraw.ImageEnhance, ImageFile, ImageFilelO, ImageFilter, ImageFont, ImageGL, ImageGrab, Imagemath, ImageOps, ImagePalette, ImagePath.ImageQt, ImageSequence, ImageStat ImageTk, ImageWin
Focus on the PIL library The most commonly used sub-libraries: Image, ImageFilter, ImageEnhance.

2. PIL library Image class analysis

Image is the most important class of PIL. It represents a picture. The method of introducing this class is as follows:

>>>from PIL import Image
Copy after login

In PIL, any image file can be represented by an Image object. The image reading and creation methods of the Image class are as follows (5 in total):

##Image.new(mode, size, color)Create a new image based on the given parameters##Image.open(StringlO.StringlO(buffer))Image.frombytes(mode, size, data)Image.verify()When opening the image file through Image, the raster data of the image will not be directly decoded or loaded, the program just The metadata information in the header of the image file is read, which identifies the format, color, size, etc. of the image. Therefore, opening a file will be very fast, regardless of how the image is stored and compressed.
Method Description
Image.open(filename) Load image file according to parameters
Get the image from the string
Create an image based on pixel data
Check the integrity of the image file and return an exception
To load an image file, the simplest form is as follows, and all subsequent operations will work on im.

>>>from PIL import Image>>>im = Image.open ("a.jpg")
Copy after login

When using IDLE interactive mode to process image files, it is recommended to use the full path of the file; if using Python file format, it is recommended to use relative paths and put the file and program in a directory. The Image class has 4 common attributes for processing images, as shown in the table (4 in total)


AttributesImage.formatImage.mode Image.sizeImage.paletteView the properties of the read image file as follows:
Description
Identifies the image format or source. If the image is not read from a file, the value is None
The color mode of the image, "L" is a grayscale image, "RGB" is a true color image, and "CMYK" is a published image
Image density and height, the unit is pixel (px), the return value is a tuple (tuple)
Palette attribute, returns an ImagePalette type
>>>print (im. format, im.size, im.mode)JPEG (900, 598) RGB
Copy after login

Image can also be read Sequence image files, including GIF, FLI, FLC, TIFF and other format files. The open() method automatically loads the first frame in the sequence when opening an image, and the seek() and tell() methods can be used to move between different frames.

Sequence image operation methods of Image class (2 in total):


Method Image.seek(frame)Image.tell()

【实例1】GIF文件图像提取
对一个GIF格式动态文件,提取其中各帧图像,并保存为文件。

from PIL import Image#读入一个GIF文件im = Image.open("pybit.gif")try:
	im.save('picframe{:02d).png'.format(im.tell()))
	while True:
		im.seek(im.tel1 ()+1)
		im.save('picframe{:02d).png'.format(im.tell()))except:print("处理结束")
Copy after login

实例1展示了一种采用try-except编写程序的方法,通过seek()方法和save()方法配合提取GIF图像格式的每一帧,并保存为文件。
Image类的图像转换和保存方法 (共3个) 如表所示。

Description
Jump and return to the specified frame in the image
Return the sequence number of the current frame
方法 描述
Image.save(filename, format) 将图像保存为filename文件名,format是图片格式
Image.convert(mode) 使用不同的参数,转换图像为新的模式
Image.thumbnail(size) 创建图像的缩略图,size是缩略图尺寸的二元元组

其中,save()方法有两个参数:文件名filename和图像格式format。如果调用时不指定保存格式,如微实例1,PIL将自动根据文件名filename后缀存储图像;如果指定格式,则按照格式存储。搭配采用open()和save()方法可以实现图像的格式转换,例如,将 jpg格式转换为png格式」代码如下。需要注意,Image 类的 save()方法主要用于保存文件到硬盘,PIL库还提供了功能更强大的格式转换方法。

im = Image.open("a.jpg")im.save("a.png")
Copy after login

Image类可以缩放和旋转图像,其中,rotate(方法以逆时旋转的角度值作为参数来旋转图像。
Image类的图像旋转和缩放方法(共2个):

方法 描述
Image.resize(size) 按size大小调整图像,生成副本
Image.rotate(angle) 按angle角度旋转图像,生成副本

Image类能够对每个像素点或者一幅RGB图像的每个通道单独进行操作。split()方法能够将RGB 图像各颜色通道提取出来;
merge()方法能够将各独立通道再合成一幅新的图像。
lmage类的图像像素和通道处理方法(共4个):

方法 描述
Image.point(func) 根据函数func的功能对每个元素进行运算,返回图像副本
Image.split() 提取RGB图像的每个颜色通道,返回图像副本
Image.merge(mode,bands) 合并通道,其中mode表示色彩,bands表示新的色彩通道
Image.blend(im1,im2,alpha) 将两幅图片iml和im2按照如下公式插值后生成新的图像:im1 (1.0-alpha) + im2 alpha

【实例2】图像的颜色交换
交换图像中的颜色。可以通过分离RGB图片的3个颜色通道实现颜色交换。

from PIL import Imageim = Image.open('a.jpg')r, g, b = im.split()om = Image.merge("RGB" , (b, g, r))om.save('aBGR.jpg')
Copy after login

运行结果:
Python image processing PIL library
原图:
Python image processing PIL library

操作图像的每个像素点需要通过函数实现,可以采用(lambda)函数和point()方法,例子如下,显示效果如图7所示。

>>>im=Image.apen('a.jpg')#打开文件>>>>r,g,b=im.splitO#获得RGB通道数据>>>>newg=g.point(lambda i:i*0.9)#将G通道颜色值变为原来的0.9>>>>newb=b.point(lambda i:i>>>om=Image.merge(im.mode,(r,newg,newb)#将3个通道合成为新图>>>>om.save('new_a.jpg')#输出图片
Copy after login

3.图像的过滤和增强

PIL库的ImageFilter类和ImageEnhance类提供了过滤图像和增强图像的方法。
ImageFilter类共提供10种预定义图像过滤方法(共10个):

方法表示 描述
ImageFilter.BLUR 图像的模糊效果
ImageFilter.CONTOUR 图像的轮廓效果
ImageFilter.DETAIL 图像的细节效果
ImageFilter.EDGE_ENHANCE 图像的边界加强效果
ImageFilter.EDGE_ENHANCE_MORE 图像的阈值边界加强效果
ImageFilter.EMBOSS 图像的浮雕效果
ImageFilter.SMOOTHL 图像的平滑效果
ImageFilter.FIND_EDGES 图像的边界效果
ImageFilter.SMOOTH_MORE 图像的阈值平滑效果
ImageFilter.SHARPEN 图像的锐化效果

利用Image类的filter()方法可以使用ImageFilter类,使用方式如下:

Image.filter(ImageFilter.fuction)
Copy after login

【实例3】图像的轮廓获取。
获取图像的轮廓,代码如下,程序执行效果如图所示,图片变得更加抽象、更具想象空间!

from PIL import Imagefrom PIL import ImageFilterim = Image.open('a.jpg')om = im.filter(ImageFilter.CONTOUR)om.save('aContour.jpg')
Copy after login

运行结果:
Python image processing PIL library
原图:
Python image processing PIL library
ImageEnhance类提供了更高级的图像增强功能,如调整色彩度、亮度、对比度、锐化等。
ImageEnhance类的图像增强和滤镜方法(共5个):

方法 描述
ImageEnhance.enhance(factor) 对选择属性的数值增强factor倍
ImageEnhance.Color(im) 调整图像的颜色平衡
ImageEnhance.Contrast(im) 调整图像的对比度
ImageEnhance.Brightness(im) 调整图像的亮度
ImageEnhance.Sharpness(im) 调整图像的锐度

【实例4】图像的对比度增强。
增强图像的对比度为初始的20倍。代码如下,程序执行效果如图7所示。

from PIL import Imagefrom PIL import ImageEnhanceim = Image.open('a.jpg')om = ImageEnhance.Contrast(im)om.enhance(20).save(aEnContrast.jpg')
Copy after login

运行结果:
Python image processing PIL library
原图:Python image processing PIL library

推荐学习:python

The above is the detailed content of Python image processing PIL library. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles