search
HomeBackend DevelopmentPython TutorialPython uses Pillow (PIL) for image operation examples

颜色与RGBA值

计算机通常将图像表示为RGB值,或者再加上alpha值(通透度,透明度),称为RGBA值。在Pillow中,RGBA的值表示为由4个整数组成的元组,分别是R、G、B、A。整数的范围0~255。RGB全0就可以表示黑色,全255代表黑色。可以猜测(255, 0, 0, 255)代表红色,因为R分量最大,G、B分量为0,所以呈现出来是红色。但是当alpha值为0时,无论是什么颜色,该颜色都不可见,可以理解为透明。

from PIL import ImageColorprint(ImageColor.getcolor('red', 'RGBA'))# 也可以只以RBG的方式查看print(ImageColor.getcolor('black', 'RGB'))
(255, 0, 0, 255)
(0, 0, 0)

图像的坐标表示

图像中左上角是坐标原点(0, 0),这和平常数学里的坐标系不太一样。这样定义的坐标系意味着,X轴是从左到右增长的,而Y轴是从上到下增长。

在Pillow中如何使用上述定义的坐标系表示一块矩形区域?许多函数或方法要求提供一个矩形元组参数。元组参数包含四个值,分别代表矩形四条边的距离X轴或者Y轴的距离。顺序是(左,顶,右,底)。右和底坐标稍微特殊,表示直到但不包括。可以理解为[左, 右)[顶, 底)这样左闭右开的区间。比如(3, 2, 8, 9)就表示了横坐标范围[3, 7];纵坐标范围[2, 8]的矩形区域。

使用Pillow操作图像

了解了一些基础知识,可以上手了。首先从读取图片开始,很多图像处理库(如opencv)都以imread()读取图片。Pillow中使用open方法。

from PIL import Image

im_path = r'F:\Jupyter Notebook\csv_time_datetime_PIL\rabbit.jpg'im = Image.open(im_path)
width, height = im.size# 宽高print(im.size, width, height)# 格式,以及格式的详细描述print(im.format, im.format_description)

im.save(r'C:\Users\Administrator\Desktop\rabbit_copy.jpg')
im.show()
(19Python uses Pillow (PIL) for image operation examples, 1080) 19Python uses Pillow (PIL) for image operation examples 1080
JPEG JPEG (ISO 10918)

im.size返回一个元组,分别是宽和高。show()方法会调用系统默认图像查看软件,打开并显示。im.format可查看图像的格式。save()可保存处理后的图片,如果未经处理,保存后的图像占用的空间(字节数)一般也与Python uses Pillow (PIL) for image operation examples像不一样,可能经过了压缩。

新建图像

Pillow也可以新建空白图像, 第一个参数是mode即颜色空间模式,第二个参数指定了图像的分辨率(宽x高),第三个参数是颜色。

  • 可以直接填入常用颜色的名称。如'red'

  • 也可以填入十六进制表示的颜色,如#FF0000表示红色。

  • 还能传入元组,比如(255, 0, 0, 255)或者(255, 0, 0)表示红色。

# 通常使用RGB模式就可以了newIm= Image.new('RGB', (100, 100), 'red')
newIm.save(r'C:\Users\Administrator\Desktop\1.png')# 也可以用RGBA模式,还有其他模式查文档吧blcakIm = Image.new('RGB',(Python uses Pillow (PIL) for image operation examples0, 100), 'red')
blcakIm.save(r'C:\Users\Administrator\Desktop\2.png')# 十六进制颜色blcakIm = Image.new('RGBA',(Python uses Pillow (PIL) for image operation examples0, 100), '#FF0000')
blcakIm.save(r'C:\Users\Administrator\Desktop\3.png')# 传入元组形式的RGBA值或者RGB值# 在RGB模式下,第四个参数失效,默认255,在RGBA模式下,也可只传入前三个值,A值默认255blcakIm = Image.new('RGB',(Python uses Pillow (PIL) for image operation examples0, 100), (255, 255, 0, 1Python uses Pillow (PIL) for image operation examples))
blcakIm.save(r'C:\Users\Administrator\Desktop\4.png')


裁剪图像

Image有个crop()方法接收一个矩形区域元组(上面有提到)。返回一个新的Image对象,是Python uses Pillow (PIL) for image operation examples的图像,对Python uses Pillow (PIL) for image operation examples没有影响。

im = Image.open(im_path)
cropedIm = im.crop((700, 100, 1Python uses Pillow (PIL) for image operation examples0, 1000))
cropedIm.save(r'C:\Users\Administrator\Desktop\cropped.png')

看下Python uses Pillow (PIL) for image operation examples和Python uses Pillow (PIL) for image operation examples的图像。

Python uses Pillow (PIL) for image operation examples

Python uses Pillow (PIL) for image operation examples

复制与粘贴图像到另一个图像

Imagecopy函数如其名会产生一个Python uses Pillow (PIL) for image operation examples像的副本,在这个副本上的任何操作不会影响到Python uses Pillow (PIL) for image operation examples像。paste()方法用于将一个图像粘贴(覆盖)在另一个图像上面。谁调用它,他就在该Image对象上直接作修改。

im = Image.open(im_path)
cropedIm = im.crop((700, 100, 1Python uses Pillow (PIL) for image operation examples0, 1000))
im.paste(cropedIm, (0, 0))
im.show()
im.save(r'C:\Users\Administrator\Desktop\paste.png')

im.show()显示图像发现这时im(即Python uses Pillow (PIL) for image operation examples)已经被改变。

Python uses Pillow (PIL) for image operation examples

这如果之后还会用到Python uses Pillow (PIL) for image operation examples的信息,由于信息被改变就很麻烦。所以paste前最好使用copy()复制一个副本,在此副本操作,不会影响到Python uses Pillow (PIL) for image operation examples信息。虽然在程序里Python uses Pillow (PIL) for image operation examples信息已改变,但由于保存文件时用的其他文件名,相当于改变没有生效,所以查看的时候Python uses Pillow (PIL) for image operation examples还是没有改变的。

im = Image.open(im_path)
cropedIm = im.crop((700, 100, 1Python uses Pillow (PIL) for image operation examples0, 1000))
copyIm = im.copy()
copyIm.paste(cropedIm, (0, 0))
im.show()
copyIm.save(r'C:\Users\Administrator\Desktop\paste.png')

这回再看Python uses Pillow (PIL) for image operation examples,没有改变了。这就保证了之后再次使用im时,里面的信息还是原汁原味。来看个有趣的例子。

im = Image.open(im_path)
cropedIm = im.crop((700, 100, 1Python uses Pillow (PIL) for image operation examples0, 1000))

crop_width, crop_height = cropedIm.size
width, height = im.size

copyIm = im.copy()for left in range(0, width, crop_width):for top in range(0, height, crop_height):
        copyIm.paste(cropedIm, (left, top))

copyIm.save(r'C:\Users\Administrator\Desktop\dupli-rabbit.png')

以Python uses Pillow (PIL) for image operation examples的图像宽度和高度为间隔,在循环内不断粘贴在副本中,这有点像是在拍证件照。

Python uses Pillow (PIL) for image operation examples

调整图像的大小

resize方法返回指定宽高度的新Image对象,接受一个含有宽高的元组作为参数。宽高的值得是整数。

im = Image.open(im_path)
width, height = im.size
resizedIm = im.resize((width, height+(19Python uses Pillow (PIL) for image operation examples-1080)))
resizedIm.save(r'C:\Users\Administrator\Desktop\resize.png')

Python uses Pillow (PIL) for image operation examples

兔子瘦了,可以看到resize不是等比例缩放的。

旋转和翻转图像

rotate()返回旋转后的新Image对象, 保持Python uses Pillow (PIL) for image operation examples像不变。逆时针旋转。

im = Image.open(im_path)
im.rotate(Python uses Pillow (PIL) for image operation examples).save(r'C:\Users\Administrator\Desktop\rotatePython uses Pillow (PIL) for image operation examples.png')
im.rotate(Python uses Pillow (PIL) for image operation examples).save(r'C:\Users\Administrator\Desktop\rotatePython uses Pillow (PIL) for image operation examples.png')
im.rotate(Python uses Pillow (PIL) for image operation examples).save(r'C:\Users\Administrator\Desktop\rotatePython uses Pillow (PIL) for image operation examples.png')
im.rotate(Python uses Pillow (PIL) for image operation examples).save(r'C:\Users\Administrator\Desktop\rotatePython uses Pillow (PIL) for image operation examples.png')
im.rotate(Python uses Pillow (PIL) for image operation examples, expand=True).save(r'C:\Users\Administrator\Desktop\rotatePython uses Pillow (PIL) for image operation examples_expand.png')

Python uses Pillow (PIL) for image operation examples

Python uses Pillow (PIL) for image operation examples

Python uses Pillow (PIL) for image operation examples

Python uses Pillow (PIL) for image operation examples

Python uses Pillow (PIL) for image operation examples

由上到下,分别是旋转了Python uses Pillow (PIL) for image operation examples°,Python uses Pillow (PIL) for image operation examples°, Python uses Pillow (PIL) for image operation examples°、普通的Python uses Pillow (PIL) for image operation examples°,加了参数expand=True旋转的Python uses Pillow (PIL) for image operation examples°。expand放大了图像尺寸(变成了2174x1672),使得边角的图像不被裁剪(四个角刚好贴着图像边缘)。再看旋转Python uses Pillow (PIL) for image operation examples°、Python uses Pillow (PIL) for image operation examples°时候图像被裁剪了,但是如下查看图像的宽高,确是和Python uses Pillow (PIL) for image operation examples一样,搞不懂。

imPython uses Pillow (PIL) for image operation examples = Image.open(r'C:\Users\Administrator\Desktop\rotatePython uses Pillow (PIL) for image operation examples.png')
imPython uses Pillow (PIL) for image operation examples = Image.open(r'C:\Users\Administrator\Desktop\rotatePython uses Pillow (PIL) for image operation examples.png')# 宽高信息并没有改变print(imPython uses Pillow (PIL) for image operation examples.size, imPython uses Pillow (PIL) for image operation examples.size)
(19Python uses Pillow (PIL) for image operation examples, 1080) (19Python uses Pillow (PIL) for image operation examples, 1080)

图像的镜面翻转。transpose()函数可以实现,必须传入Image.FLIP_LEFT_RIGHT或者Image.FLIP_TOP_BOTTOM,第一个是Python uses Pillow (PIL) for image operation examples,第二个是Python uses Pillow (PIL) for image operation examples。

im = Image.open(im_path)
im.transpose(Image.FLIP_LEFT_RIGHT).save(r'C:\Users\Administrator\Desktop\transepose_lr.png')
im.transpose(Image.FLIP_TOP_BOTTOM).save(r'C:\Users\Administrator\Desktop\transepose_tb.png')

Python uses Pillow (PIL) for image operation examples

Python uses Pillow (PIL) for image operation examples看不出来,Python uses Pillow (PIL) for image operation examples就是水平对称的...

Python uses Pillow (PIL) for image operation examples

Python uses Pillow (PIL) for image operation examples就明显了...

图像过滤

Pillow使用ImageFilter可以简单做到图像的模糊、边缘增强、锐利、平滑等常见操作。

from PIL import Image, ImageFilter

im = Image.open(im_path)# 高斯模糊im.filter(ImageFilter.GaussianBlur).save(r'C:\Users\Administrator\Desktop\GaussianBlur.jpg')# 普通模糊im.filter(ImageFilter.BLUR).save(r'C:\Users\Administrator\Desktop\BLUR.jpg')# 边缘增强im.filter(ImageFilter.EDGE_ENHANCE).save(r'C:\Users\Administrator\Desktop\EDGE_ENHANCE.jpg')# 找到边缘im.filter(ImageFilter.FIND_EDGES).save(r'C:\Users\Administrator\Desktop\FIND_EDGES.jpg')# 浮雕im.filter(ImageFilter.EMBOSS).save(r'C:\Users\Administrator\Desktop\EMBOSS.jpg')# 轮廓im.filter(ImageFilter.CONTOUR).save(r'C:\Users\Administrator\Desktop\CONTOUR.jpg')# 锐化im.filter(ImageFilter.SHARPEN).save(r'C:\Users\Administrator\Desktop\SHARPEN.jpg')# 平滑im.filter(ImageFilter.SMOOTH).save(r'C:\Users\Administrator\Desktop\SMOOTH.jpg')# 细节im.filter(ImageFilter.DETAIL).save(r'C:\Users\Administrator\Desktop\DETAIL.jpg')

另外,若是要进行图案、文字的绘制,可使用ImageDraw。Pillow还有其他强大功能,就不一一列举了。

其实,Pillow只是个基础的图像处理库。若不深入图像处理,已经够用。专业人士使用opencv是更好地选择。Python中使用import cv2开始使用吧!

The above is the detailed content of Python uses Pillow (PIL) for image operation examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python vs. C  : Pros and Cons for DevelopersPython vs. C : Pros and Cons for DevelopersApr 17, 2025 am 12:04 AM

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

Python: Time Commitment and Learning PacePython: Time Commitment and Learning PaceApr 17, 2025 am 12:03 AM

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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