PIL Python Imaging Library (PIL)

2024-09-08 08:18
文章标签 python pil library imaging

本文主要是介绍PIL Python Imaging Library (PIL),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

介绍

        把Python的基础知识学习后,尝试一下如何安装、加载、使用非标准库,选择了图像处理模块PIL。

        Python Imaging Library (PIL)是PythonWare公司提供的免费的图像处理工具包,是python下的图像处理模块,支持多种格式,并提供强大的图形与图像处理功能。虽然在这个软件包上要实现类似MATLAB中的复杂的图像处理算法并不太适合,但是Python的快速开发能力以及面向对象等等诸多特点使得它非常适合用来进行原型开发。对于简单的图像处理或者大批量的简单图像处理任务,python+PIL是很好的选择。

        PIL 具备(但不限于) 以下的能力:

  • 数十种图档格式的读写能力。 常见的JPEG, PNG, BMP, GIF, TIFF 等格式,都在PIL 的支援之列。 另外,PIL 也支援黑白、灰阶、自订调色盘、RGB true color、带有透明属性的RBG true color、CMYK 及其它数种的影像模式。相当齐全。 
  • 基本的影像资料操作:裁切、平移、旋转、改变尺寸、调置(transpose)、剪下与贴上等等。 
  • 强化图形:亮度、色调、对比、锐利度。 
  • 色彩处理。 
  • PIL 提供十数种滤镜(filter)。 当然,这个数目远远不能与Photoshop® 或GIMP® 这样的专业特效处理软体相比;但PIL 提供的这些滤镜可以用在Python 程式里面,提供批次化处理的能力。 
  • PIL 可以在影像中绘图制点、线、面、几何形状、填满、文字等等。

       目前PIL的官方最新版本为1.1.7(官方下载地址:这里),支持的版本为python 2.5, 2.6, 2.7,并不支持python3.x,但有高手把它重新编译生成python3下可安装的exe了。这一非官方下载地址:这里。

       这里是PIL的使用手册,这里有中文版。

------------------------------------------------------------------------------------------------------------------------------------------

安装

        由于目前暂未出支持3.x的PIL版本,所以从上述非官方地址中下载了支持3.3的win32版本。需要注意该地址中有两点说明:

[plain]  view plain copy
  1. Note: use `from PIL import Image` instead of `import Image`.  
  2. Note: this fork contains bug fixes and enhancements.  

        下载完成后 ,基本一直“next”即可安装。

------------------------------------------------------------------------------------------------------------------------------------------

使用

        在PIL中,任何一副图像都是用一个Image对象表示,而这个类由和它同名的模块导出,因此,要加载一副图像,最简单的形式是这样的:

[python]  view plain copy
  1. import Image   
  2. img = Image.open(“test.jpg”)   

        由于使用的是非官方的支持3.3版本的PIL,并提示“use `from PIL import Image` instead of `import Image`.”所以本文加载图像是用如下方式:

[python]  view plain copy
  1. from PIL import Image  
  2. img = Image.open("test.jpg")  
        PIL提供了丰富的功能模块:Image,ImageDraw,ImageEnhance,ImageFile等等。最常用到的模块是Image,ImageDraw,ImageEnhance这三个模块。

(1)Image模块

       Image模块是PIL最基本的模块,其中导出了Image类,一个Image类实例对象就对应了一副图像。同时,Image模块还提供了很多有用的函数。打开一副图像文件 :

[python]  view plain copy
  1. from PIL import Image  
  2. img = Image.open("test.jpg")  

这将返回一个Image类实例对象,后面的所有的操作都是在img上完成的。

        显示一幅已经载入的图片:

[python]  view plain copy
  1. img.show()  


        

        调整图像大小

[python]  view plain copy
  1. from PIL import Image  
  2. img = Image.open("test.jpg")  
  3. new_img = img.resize((128128), Image.BILINEAR)  
  4. new_img.save("new_img.jpg")  

原来的图像大小是256x256,现在,保存的new_img.jpg的大小是128x128。如下:



        旋转图像: 

        现在我们把刚才调整过大小的图像旋转45度: 

[python]  view plain copy
  1. from PIL import Image  
  2. img = Image.open("test.jpg")  
  3. new_img = img.resize((128128), Image.BILINEAR)  
  4. rot_img = new_img.rotate(45)  
  5. rot_img.save("rot_img.jpg")  



        格式转换
        假设我们要把上面生成的rot_img.jpg转换成bmp图像,要做到这一点这太简单了:只需要在上面的代码后面添加下面这样一行即可: 

[python]  view plain copy
  1. rot_img.save("con_img.bmp")   

此处save函数只有一个参数,是一个包含文件名和扩展名的字符串。Image类中的save函数在你未指定保存的格式时,自动根据文件名后缀完成格式转换。另外一种调用方式是:

[python]  view plain copy
  1. img.save('con_img','bmp')  

注:第一个参数为你要指定保存的文件名,第二个参数为你要指定保存的图像格式。


        直方图统计: 

        Image类实例的histogram()方法能够对直方图数据进行统计,并将结果做为一个列表(list)返回。比如,我们对上面的旋转后生成的图像进行直方图统计:

[python]  view plain copy
  1. from PIL import Image  
  2. img = Image.open("test.jpg")  
  3. new_img = img.resize((128128), Image.BILINEAR)  
  4. rot_img = new_img.rotate(45)  
  5. print (rot_img.histogram())  


(2)ImageDraw模块

         ImageDraw模块提供了基本的图形能力,这里的图形能力指的主要是图形的绘制能力。PIL库提供了比较丰富的图形绘制函数,可以绘制直线、弧线、矩形、多边形、椭圆、扇形等等。ImageDraw实现了一个Draw类,所有的图形绘制功能都是在Draw类实例的方法中实现的。

        实例化一个Draw类实例很简单:

[python]  view plain copy
  1. from PIL import Image, ImageDraw  
  2. img = Image.open("test.jpg")  
  3. draw = ImageDraw.Draw(img)  
  4. #.....  
  5. img.save("new.jpg")  


        绘制直线

[python]  view plain copy
  1. from PIL import Image, ImageDraw  
  2. img = Image.open("test.jpg")  
  3. draw = ImageDraw.Draw(img)  
  4. width, height = img.size  
  5. draw.line( ( (0,0), (width-1, height-1)), fill=255)  
  6. draw.line( ( (0,height-1), (width-10)), fill=255)  
  7. img.save("cross_line.jpg")  



        绘制圆: 

[python]  view plain copy
  1. from PIL import Image, ImageDraw  
  2. img = Image.open("test.jpg")  
  3. draw = ImageDraw.Draw(img)  
  4. width, height = img.size  
  5. draw.arc( (00, width-1, height-1), 0360, fill=255)  
  6. img.save("circle.jpg")  




(3)ImageEnhance模块

        这个模块提供了一个常用的图像增强工具箱。可以用来进行色彩增强、亮度增强、对比度增强、图像尖锐化等等增强操作。所有操作都有相同形式的接口——通过相应类的enhance方法实现:色彩增强通过Color类的enhance方法实现;亮度增强通过Brightness类的enhance方法实现;对比度增强通过Contrast类的enhance方法实现;尖锐化通过Sharpness类的enhance方法实现。所有的操作都需要向类的构造函数传递一个Image对象作为参数,这个参数定义了增强作用的对象。同时所有的操作都返回一个新的Image对象。如果传给enhance方法的参数是1.0,则不对原图像做任何改变,直接返回原图像的一个拷贝。

        这个模块很容易完全掌握,因为它只有Color、Contrast、Sharpness、Brightness四个类;并且每个类都只有两个函数__init__和enhance函数,并且这四个类的使用方式和成员函数的使用方式也都是一样的(只需要一个factor因子)。

        亮度增强: 

[python]  view plain copy
  1. from PIL import Image, ImageEnhance  
  2. img = Image.open("test.jpg")  
  3. brightness = ImageEnhance.Brightness(img)  
  4. bright_img = brightness.enhance(2.0)  
  5. bright_img.save("bright.jpg")  



        图像尖锐化: 

[python]  view plain copy
  1. from PIL import Image, ImageEnhance  
  2. img = Image.open("test.jpg")  
  3. sharpness = ImageEnhance.Sharpness(img)  
  4. sharp_img = sharpness.enhance(7.0)  
  5. sharp_img.save("sharp.jpg")  



        对比度增强: 

[python]  view plain copy
  1. from PIL import Image, ImageEnhance  
  2. img = Image.open("test.jpg")  
  3. contrast = ImageEnhance.Contrast(img)  
  4. contrast_img = contrast.enhance(2.0)  
  5. contrast_img.save("contrast.jpg")  



        色彩增强

[python]  view plain copy
  1. from PIL import Image, ImageEnhance  
  2. img = Image.open("test.jpg")  
  3. color = ImageEnhance.Color(img)  
  4. color_img = color.enhance(3.0)  
  5. color_img.save("color.jpg")  


(4)ImageChops模块

        这个模块主要包括对图片的算术运算,叫做通道运算(channel operations)。这个模块可以用于多种途径,包括一些特效制作,图片整合,算数绘图等等方面。

        图片反色,类似于集合操作中的求补集,最大值为Max,每个像素做减法,取出反色。

        公式:out = MAX - image

[python]  view plain copy
  1. ImageChops.invert(image)   

        

        比较两个图片(逐像素的比较),返回一个新的图片,这个新的图片是将两张图片中的较淡的部分的叠加。也即使说,在某一点上,两张图中,哪个的值小则取之。

        公式:out = max(img1, img2)

[python]  view plain copy
  1. ImageChops.lighter(image1, image2)   

         darker :与lighter正好相反。

        公式:out = min(img1, img2)

[python]  view plain copy
  1. ImageChops.darker(image1, image2)    

         求出两张图片的绝对值,逐像素的做减法

        公式:out = abs(img1, img2)

[python]  view plain copy
  1. ImageChops.difference(image1, image2)  

         将两张图片互相叠加 ,如果用纯黑色与某图片进行叠加操作,会得到一个纯黑色的图片。如果用纯白色与图片作叠加,图片不受影响。

        公式:out = img1 * img2 / MAX  (可以看到,如果时白色,MAX和MAX会约去,返回原始图片)

[python]  view plain copy
  1. ImageChops.multiply(image1, image2)    

         screen:先反色,后叠加

        公式:out = MAX - ((MAX - image1) * (MAX - image2) / MAX)

[python]  view plain copy
  1. ImageChops.screen(image1, image2)    

         add :对两张图片进行算术加法,按照以下公式进行计算

        公式:out = (img1+img2) / scale + offset

如果尺度和偏移被忽略的化,scale=1.0, offset=0.0,即out = img1 + img2

[python]  view plain copy
  1. ImageChops.add(img1, img2, scale, offset)    

         subtract :对两张图片进行算术减法

        公式:out = (img1-img2) / scale + offset

[python]  view plain copy
  1. ImageChops.subtract(img1, img2, scale, offset)    


(5)ImageColor模块

        The ImageColor module contains colour tables and converters from CSS3-style colour specifiers to RGB tuples. This module is used by Image.new and the ImageDraw module, among others.

        详见:这里

        getrgb(color) ⇒ (red, green, blue)
Convert a colour string to an RGB tuple. If the string cannot be parsed, this function raises a ValueError exception.

(6)ImageFile模块

       The ImageFile module provides support functions for the image open and save functions.
        In addition, it provides a Parser class which can be used to decode an image piece by piece (e.g. while receiving it over a network connection). This class implements the same consumer interface as the standard sgmllib and xmllib modules.

        详见:这里

   

        ImageFile.Parser() => Parser instance
Creates a parser object. Parsers cannot be reused.

        parser.feed(data)
Feed a string of data to the parser. This method may raise an IOError exception.

        parser.close() => image or None
Tells the parser to finish decoding. If the parser managed to decode an image, it returns an Image object. Otherwise, this method raises an IOError exception.


       Example(Parse An Image):

[python]  view plain copy
  1. import ImageFile  
  2.   
  3. fp = open("lena.pgm""rb")  
  4.   
  5. p = ImageFile.Parser()  
  6.   
  7. while 1:  
  8.     s = fp.read(1024)  
  9.     if not s:  
  10.         break  
  11.     p.feed(s)  
  12.   
  13. im = p.close()  
  14.   
  15. im.save("copy.jpg")  


(7)ImageFilter模块

        ImageFilter是PIL的滤镜模块,当前版本支持10种加强滤镜,通过这些预定义的滤镜,可以方便的对图片进行一些过滤操作,从而去掉图片中的噪音(部分的消除),这样可以降低将来处理的复杂度(如模式识别等)。

滤镜名称含义
ImageFilter.BLUR模糊滤镜
ImageFilter.CONTOUR轮廓
ImageFilter.DETAIL

ImageFilter.EDGE_ENHANCE


边界加强
ImageFilter.EDGE_ENHANCE_MORE边界加强(阀值更大)
ImageFilter.EMBOSS浮雕滤镜
ImageFilter.FIND_EDGES边界滤镜
ImageFilter.SMOOTH平滑滤镜
ImageFilter.SMOOTH_MORE平滑滤镜(阀值更大)
ImageFilter.SHARPEN锐化滤镜

        要使用PIL的滤镜功能,需要引入ImageFilter模块。

[python]  view plain copy
  1. import Image, ImageFilter  
  2.   
  3. def filterDemo():  
  4.     img = Image.open("test.jpg")  
  5.     imgfilted = img.filter(ImageFilter.SHARPEN)  
  6.     #imgfilted.show()  
  7.     imgfilted.save("sharpen.jpg")  
  8.   
  9. if __name__ == "__main__":  
  10.     filterDemo()  


(8)ImageFont模块

        The ImageFont module defines a class with the same name. Instances of this class store bitmap fonts, and are used with the text method of the ImageDraw class.

[python]  view plain copy
  1. import ImageFont, ImageDraw  
  2.   
  3. draw = ImageDraw.Draw(image)  
  4.   
  5. # use a bitmap font  
  6. font = ImageFont.load("arial.pil")  
  7.   
  8. draw.text((1010), "hello", font=font)  
  9.   
  10. # use a truetype font  
  11. font = ImageFont.truetype("arial.ttf"15)  
  12.   
  13. draw.text((1025), "world", font=font)  


(9)ImageGrab模块

The ImageGrab module can be used to copy the contents of the screen or the clipboard to a PIL image memory.
The current version works on Windows only.


ImageGrab.grab() => image
ImageGrab.grab(bbox) => image
Take a snapshot of the screen, and return an "RGB" image. The bounding box argument can be used to copy only a part of the screen.


ImageGrab.grabclipboard() => image or list of strings or None
Take a snapshot of the clipboard contents, and return an image object or a list of file names. If the clipboard doesn't contain image data, this function returns None.
You can use isinstance to check if the function returned a valid image object, or something else:

[python]  view plain copy
  1. im = ImageGrab.grabclipboard()  
  2.   
  3. if isinstance(im, Image.Image):  
  4.     ... got an image ...  
  5. elif im:  
  6.    for filename in im:  
  7.        try:  
  8.            im = Image.open(filename)  
  9.        except IOError:  
  10.            pass # ignore this file  
  11.        else:  
  12.            ... got an image ...  
  13. else:  
  14.     ... clipboard empty ...  


(10)ImageMath模块

        ImageMath 模块可以用来计算"图像表达式"。这个模块仅提供一个eval函数,它带一个表达式串以及一幅或多幅图像作参数。这个模块仅在 PIL Plus 包中可用。

        详见:这里


[python]  view plain copy
  1. import Image, ImageMath  
  2.   
  3. im1 = Image.open("image1.jpg")  
  4. im2 = Image.open("image2.jpg")  
  5.   
  6. out = ImageMath.eval("convert(min(a, b), 'L')", a=im1, b=im2)  
  7. out.save("result.png")  

(11)ImageOps模块

        The ImageOps module contains a number of 'ready-made' image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images.

        详见:这里


(12)ImagePalette模块

        要使用ImagePalette 类和相关的函数,要导入ImagePalette 模块。

        详见:这里

[python]  view plain copy
  1. #1. 将调色板添加到图像 (Sequence Syntax)  
  2. palette = []  
  3. for i in range(256):  
  4.     palette.extend((i, i, i)) # grayscale wedge  
  5.   
  6. assert len(palette) == 768  
  7.   
  8. im.putpalette(palette)  
  9.    
  10.   
  11. #2. 将调色板添加到图像 (Not Yet Supported)  
  12. import ImagePalette  
  13.   
  14. palette = ImagePalette.ImagePalette("RGB")  
  15. palette.putdata(...)  
  16.   
  17. im.putpalette(palette)  
  18.    
  19.   
  20. #3. Getting the Palette Contents Using Resize/Convert  
  21. assert im.mode == "P"  
  22.   
  23. lut = im.resize((2561))  
  24. lut.putdata(range(256))  
  25. lut = lut.convert("RGB").getdata()   
  26.   
  27. # lut now contains a sequence of (r, g, b) tuples  


(13)ImagePath模块

        ImagePath 模块用来存储和操作二维向量数据。路径对象可以被传到ImageDraw模块中的方法中。

        详见:这里


        ImagePath.Path(coordinates) => Path instance
创建一个路径对象。坐标表coordinates可以是任何包含2元组 [ (x, y), ... ] 或者数字值 [ x, y, ... ]的序列对象。

(14)ImageQt模块

        The ImageQt module contains support to create PyQt4 QImage objects from PIL images.

        详见:这里


        ImageQt.ImageQt(image)
Creates an ImageQt object from a PIL image object. 

(15)ImageSequence模块

        ImageSequence 模块包含让你能够跌代一个图像序列的包装类。

        详见:这里

        ImageSequence.Iterator(image) => Iterator instance
创建一个Iterator 对象让你可以循环遍历一个序列中的所有帧。

        Iterator 类实现 [] 运算符(Operator [] )
你可以用大于等于0的整数作参数调用这个运算符。如果没有足够的帧,跌代子会抛出一个IndexError异常。

[python]  view plain copy
  1. import Image, ImageSequence  
  2.   
  3. im = Image.open("animation.fli")  
  4.   
  5. index = 1  
  6. for frame in ImageSequence.Iterator(im):  
  7.     frame.save("frame%d.png" % index)  
  8.     index = index + 1  


(16)ImageStat模块

        The ImageStat module calculates global statistics for an image, or for a region of an image.

        详见:这里

        stat.count
        stat.sum
        stat.mean
        stat.stddev

(17)ImageTk模块

        The ImageTk module contains support to create and modify Tkinter BitmapImage and PhotoImage objects from PIL images.

        详见:这里

[python]  view plain copy
  1. ImageTk.BitmapImage(image, options)  
  2. ImageTk.PhotoImage(image)  
  3. photo.paste(image, box)  


(18)ImageWin模块

        The ImageWin module contains support to create and display images on Windows.

        详见:这里

        ImageWin can be used with PythonWin and other user interface toolkits that provide access to Windows device contexts or window handles. For example, Tkinter makes the window handle available via the winfo_id method:

[python]  view plain copy
  1. dib = ImageWin.Dib(...)  
  2.   
  3. hwnd = ImageWin.HWND(widget.winfo_id())  
  4. dib.draw(hwnd, xy)  


(19)PSDraw模块

        The PSDraw module provides simple print support for Postscript printers. You can print text, graphics and images through this module.
        详见:这里


[python]  view plain copy
  1. ps.line(from, to)  
  2. ps.rectangle(box)  
  3. ps.text(position, text)  
  4. ps.image(box, image, dpi=None)  


------------------------------------------------------------------------------------------------------------------------------------------

参考资料

(1). 《在python3下用PIL做图像处理》
(2). 《用Python进行图像处理》

(3).《python图像处理之初窥门径》

(4).  PIL的《handbook》

这篇关于PIL Python Imaging Library (PIL)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1147596

相关文章

python: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学

nudepy,一个有趣的 Python 库!

更多资料获取 📚 个人网站:ipengtao.com 大家好,今天为大家分享一个有趣的 Python 库 - nudepy。 Github地址:https://github.com/hhatto/nude.py 在图像处理和计算机视觉应用中,检测图像中的不适当内容(例如裸露图像)是一个重要的任务。nudepy 是一个基于 Python 的库,专门用于检测图像中的不适当内容。该

pip-tools:打造可重复、可控的 Python 开发环境,解决依赖关系,让代码更稳定

在 Python 开发中,管理依赖关系是一项繁琐且容易出错的任务。手动更新依赖版本、处理冲突、确保一致性等等,都可能让开发者感到头疼。而 pip-tools 为开发者提供了一套稳定可靠的解决方案。 什么是 pip-tools? pip-tools 是一组命令行工具,旨在简化 Python 依赖关系的管理,确保项目环境的稳定性和可重复性。它主要包含两个核心工具:pip-compile 和 pip

HTML提交表单给python

python 代码 from flask import Flask, request, render_template, redirect, url_forapp = Flask(__name__)@app.route('/')def form():# 渲染表单页面return render_template('./index.html')@app.route('/submit_form',

Python QT实现A-star寻路算法

目录 1、界面使用方法 2、注意事项 3、补充说明 用Qt5搭建一个图形化测试寻路算法的测试环境。 1、界面使用方法 设定起点: 鼠标左键双击,设定红色的起点。左键双击设定起点,用红色标记。 设定终点: 鼠标右键双击,设定蓝色的终点。右键双击设定终点,用蓝色标记。 设置障碍点: 鼠标左键或者右键按着不放,拖动可以设置黑色的障碍点。按住左键或右键并拖动,设置一系列黑色障碍点

Python:豆瓣电影商业数据分析-爬取全数据【附带爬虫豆瓣,数据处理过程,数据分析,可视化,以及完整PPT报告】

**爬取豆瓣电影信息,分析近年电影行业的发展情况** 本文是完整的数据分析展现,代码有完整版,包含豆瓣电影爬取的具体方式【附带爬虫豆瓣,数据处理过程,数据分析,可视化,以及完整PPT报告】   最近MBA在学习《商业数据分析》,大实训作业给了数据要进行数据分析,所以先拿豆瓣电影练练手,网络上爬取豆瓣电影TOP250较多,但对于豆瓣电影全数据的爬取教程很少,所以我自己做一版。 目

【Python报错已解决】AttributeError: ‘list‘ object has no attribute ‘text‘

🎬 鸽芷咕:个人主页  🔥 个人专栏: 《C++干货基地》《粉丝福利》 ⛺️生活的理想,就是为了理想的生活! 文章目录 前言一、问题描述1.1 报错示例1.2 报错分析1.3 解决思路 二、解决方法2.1 方法一:检查属性名2.2 步骤二:访问列表元素的属性 三、其他解决方法四、总结 前言 在Python编程中,属性错误(At