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中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

利用python实现对excel文件进行加密

《利用python实现对excel文件进行加密》由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴... 目录前言方法一:使用pywin32库(仅限Windows)方法二:使用msoffcrypto-too

使用Python实现矢量路径的压缩、解压与可视化

《使用Python实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1

python获取网页表格的多种方法汇总

《python获取网页表格的多种方法汇总》我们在网页上看到很多的表格,如果要获取里面的数据或者转化成其他格式,就需要将表格获取下来并进行整理,在Python中,获取网页表格的方法有多种,下面就跟随小编... 目录1. 使用Pandas的read_html2. 使用BeautifulSoup和pandas3.

Python装饰器之类装饰器详解

《Python装饰器之类装饰器详解》本文将详细介绍Python中类装饰器的概念、使用方法以及应用场景,并通过一个综合详细的例子展示如何使用类装饰器,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录1. 引言2. 装饰器的基本概念2.1. 函数装饰器复习2.2 类装饰器的定义和使用3. 类装饰