search
HomeBackend DevelopmentPython TutorialPython image processing PIL library

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

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

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")

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

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("处理结束")

实例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")

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')

运行结果:
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')#输出图片

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)

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

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

运行结果:
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')

运行结果:
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
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.