PIL Python Imaging Library (PIL)

2024-03-08 04:50
文章标签 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/786067

相关文章

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Python获取浏览器Cookies的四种方式小结

《Python获取浏览器Cookies的四种方式小结》在进行Web应用程序测试和开发时,获取浏览器Cookies是一项重要任务,本文我们介绍四种用Python获取浏览器Cookies的方式,具有一定的... 目录什么是 Cookie?1.使用Selenium库获取浏览器Cookies2.使用浏览器开发者工具

Python实现批量提取BLF文件时间戳

《Python实现批量提取BLF文件时间戳》BLF(BinaryLoggingFormat)作为Vector公司推出的CAN总线数据记录格式,被广泛用于存储车辆通信数据,本文将使用Python轻松提取... 目录一、为什么需要批量处理 BLF 文件二、核心代码解析:从文件遍历到数据导出1. 环境准备与依赖库

Python Web框架Flask、Streamlit、FastAPI示例详解

《PythonWeb框架Flask、Streamlit、FastAPI示例详解》本文对比分析了Flask、Streamlit和FastAPI三大PythonWeb框架:Flask轻量灵活适合传统应用... 目录概述Flask详解Flask简介安装和基础配置核心概念路由和视图模板系统数据库集成实际示例Stre

Python实现PDF按页分割的技术指南

《Python实现PDF按页分割的技术指南》PDF文件处理是日常工作中的常见需求,特别是当我们需要将大型PDF文档拆分为多个部分时,下面我们就来看看如何使用Python创建一个灵活的PDF分割工具吧... 目录需求分析技术方案工具选择安装依赖完整代码实现使用说明基本用法示例命令输出示例技术亮点实际应用场景扩

Python错误AttributeError: 'NoneType' object has no attribute问题的彻底解决方法

《Python错误AttributeError:NoneTypeobjecthasnoattribute问题的彻底解决方法》在Python项目开发和调试过程中,经常会碰到这样一个异常信息... 目录问题背景与概述错误解读:AttributeError: 'NoneType' object has no at

Python使用openpyxl读取Excel的操作详解

《Python使用openpyxl读取Excel的操作详解》本文介绍了使用Python的openpyxl库进行Excel文件的创建、读写、数据操作、工作簿与工作表管理,包括创建工作簿、加载工作簿、操作... 目录1 概述1.1 图示1.2 安装第三方库2 工作簿 workbook2.1 创建:Workboo

基于Python实现简易视频剪辑工具

《基于Python实现简易视频剪辑工具》这篇文章主要为大家详细介绍了如何用Python打造一个功能完备的简易视频剪辑工具,包括视频文件导入与格式转换,基础剪辑操作,音频处理等功能,感兴趣的小伙伴可以了... 目录一、技术选型与环境搭建二、核心功能模块实现1. 视频基础操作2. 音频处理3. 特效与转场三、高

Python实现中文文本处理与分析程序的示例详解

《Python实现中文文本处理与分析程序的示例详解》在当今信息爆炸的时代,文本数据的处理与分析成为了数据科学领域的重要课题,本文将使用Python开发一款基于Python的中文文本处理与分析程序,希望... 目录一、程序概述二、主要功能解析2.1 文件操作2.2 基础分析2.3 高级分析2.4 可视化2.5

一文解密Python进行监控进程的黑科技

《一文解密Python进行监控进程的黑科技》在计算机系统管理和应用性能优化中,监控进程的CPU、内存和IO使用率是非常重要的任务,下面我们就来讲讲如何Python写一个简单使用的监控进程的工具吧... 目录准备工作监控CPU使用率监控内存使用率监控IO使用率小工具代码整合在计算机系统管理和应用性能优化中,监