Python图像处理库Pillow入门
http://python.jobbole.com/84956/
Pillow是Python里的图像处理库(PIL:Python Image Library),提供了了广泛的文件格式支持,强大的图像处理能力,主要包括图像储存、图像显示、格式转换以及基本的图像处理操作等。
1)使用 Image 类
PIL最重要的类是 Image class, 你可以通过多种方法创建这个类的实例;你可以从文件加载图像,或者处理其他图像, 或者从 scratch 创建。
要从文件加载图像,可以使用open( )函数,在Image模块中:
>>> im = Image.open("E:/photoshop/1.jpg")
|
1
2
|
>>> from PIL import Image
>>> im = Image.open("E:/photoshop/1.jpg")
|
加载成功后,将返回一个Image对象,可以通过使用示例属性查看文件内容:
('JPEG', (600, 351), 'RGB')
>>>
|
1
2
3
|
>>> print(im.format, im.size, im.mode)
('JPEG', (600, 351), 'RGB')
>>>
|
format 这个属性标识了图像来源。如果图像不是从文件读取它的值就是None。size属性是一个二元tuple,包含width和height(宽度和高度,单位都是px)。 mode 属性定义了图像bands的数量和名称,以及像素类型和深度。常见的modes 有 “L” (luminance) 表示灰度图像, “RGB” 表示真彩色图像, and “CMYK” 表示出版图像。
如果文件打开错误,返回 IOError 错误。
只要你有了 Image 类的实例,你就可以通过类的方法处理图像。比如,下列方法可以显示图像:
|
1
|
im.show()
|
2)读写图像
PIL 模块支持大量图片格式。使用在 Image 模块的 open()
函数从磁盘读取文件。你不需要知道文件格式就能打开它,这个库能够根据文件内容自动确定文件格式。要保存文件,使用 Image 类的 save()
方法。保存文件的时候文件名变得重要了。除非你指定格式,否则这个库将会以文件名的扩展名作为格式保存。
加载文件,并转化为png格式:
from PIL import Image
import os
import sys
for infile in sys.argv[1:]:
f,e = os.path.splitext(infile)
outfile = f +".png"
if infile != outfile:
try:
Image.open(infile).save(outfile)
except IOError:
print("Cannot convert", infile)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
"Python Image Library Test"
from PIL import Image
import os
import sys
for infile in sys.argv[1:]:
f,e = os.path.splitext(infile)
outfile = f +".png"
if infile != outfile:
try:
Image.open(infile).save(outfile)
except IOError:
print("Cannot convert", infile)
|
save() 方法的第二个参数可以指定文件格式。
3)创建缩略图
缩略图是网络开发或图像软件预览常用的一种基本技术,使用Python的Pillow图像库可以很方便的建立缩略图,如下:
size = (128,128)
for infile in glob.glob("E:/photoshop/*.jpg"):
f, ext = os.path.splitext(infile)
img = Image.open(infile)
img.thumbnail(size,Image.ANTIALIAS)
img.save(f+".thumbnail","JPEG")
|
1
2
3
4
5
6
7
|
# create thumbnail
size = (128,128)
for infile in glob.glob("E:/photoshop/*.jpg"):
f, ext = os.path.splitext(infile)
img = Image.open(infile)
img.thumbnail(size,Image.ANTIALIAS)
img.save(f+".thumbnail","JPEG")
|
上段代码对photoshop下的jpg图像文件全部创建缩略图,并保存,glob模块是一种智能化的文件名匹配技术,在批图像处理中经常会用到。
注意:Pillow库不会直接解码或者加载图像栅格数据。当你打开一个文件,只会读取文件头信息用来确定格式,颜色模式,大小等等,文件的剩余部分不会主动处理。这意味着打开一个图像文件的操作十分快速,跟图片大小和压缩方式无关。
4)图像的剪切、粘贴与合并操作
Image 类包含的方法允许你操作图像部分选区,PIL.Image.Image.crop 方法获取图像的一个子矩形选区,如:
im = Image.open("E:/photoshop/lena.jpg")
box = (100,100,300,300)
region = im.crop(box)
|
1
2
3
4
|
# crop, paste and merge
im = Image.open("E:/photoshop/lena.jpg")
box = (100,100,300,300)
region = im.crop(box)
|
矩形选区有一个4元元组定义,分别表示左、上、右、下的坐标。这个库以左上角为坐标原点,单位是px,所以上诉代码复制了一个 200×200 pixels 的矩形选区。这个选区现在可以被处理并且粘贴到原图。
im.paste(region, box)
|
1
2
|
region = region.transpose(Image.ROTATE_180)
im.paste(region, box)
|
当你粘贴矩形选区的时候必须保证尺寸一致。此外,矩形选区不能在图像外。然而你不必保证矩形选区和原图的颜色模式一致,因为矩形选区会被自动转换颜色。
5)分离和合并颜色通道
对于多通道图像,有时候在处理时希望能够分别对每个通道处理,处理完成后重新合成多通道,在Pillow中,很简单,如下:
im = Image.merge("RGB", (r,g,b))
|
1
2
|
r,g,b = im.split()
im = Image.merge("RGB", (r,g,b))
|
对于split( )函数,如果是单通道的,则返回其本身,否则,返回各个通道。
6)几何变换
对图像进行几何变换是一种基本处理,在Pillow中包括resize( )和rotate( ),如用法如下:
out = im.rotate(45) # degree conter-clockwise
|
1
2
|
out = im.resize((128,128))
out = im.rotate(45) # degree conter-clockwise
|
其中,resize( )函数的参数是一个新图像大小的元祖,而rotate( )则需要输入顺时针的旋转角度。在Pillow中,对于一些常见的旋转作了专门的定义:
out = im.transpose(Image.FLIP_TOP_BOTTOM)
out = im.transpose(Image.ROTATE_90)
out = im.transpose(Image.ROTATE_180)
out = im.transpose(Image.ROTATE_270)
|
1
2
3
4
5
|
out = im.transpose(Image.FLIP_LEFT_RIGHT)
out = im.transpose(Image.FLIP_TOP_BOTTOM)
out = im.transpose(Image.ROTATE_90)
out = im.transpose(Image.ROTATE_180)
out = im.transpose(Image.ROTATE_270)
|
7)颜色空间变换
在处理图像时,根据需要进行颜色空间的转换,如将彩色转换为灰度:
gray = im.convert("L")
|
1
2
|
cmyk = im.convert("CMYK")
gray = im.convert("L")
|
8)图像滤波
图像滤波在ImageFilter 模块中,在该模块中,预先定义了很多增强滤波器,可以通过filter( )函数使用,预定义滤波器包括:
BLUR、CONTOUR、DETAIL、EDGE_ENHANCE、EDGE_ENHANCE_MORE、EMBOSS、FIND_EDGES、SMOOTH、SMOOTH_MORE、SHARPEN。其中BLUR就是均值滤波,CONTOUR找轮廓,FIND_EDGES边缘检测,使用该模块时,需先导入,使用方法如下:
imgF = Image.open("E:/photoshop/lena.jpg")
outF = imgF.filter(ImageFilter.DETAIL)
conF = imgF.filter(ImageFilter.CONTOUR)
edgeF = imgF.filter(ImageFilter.FIND_EDGES)
imgF.show()
outF.show()
conF.show()
edgeF.show()
|
1
2
3
4
5
6
7
8
9
10
|
from PIL import ImageFilter
imgF = Image.open("E:/photoshop/lena.jpg")
outF = imgF.filter(ImageFilter.DETAIL)
conF = imgF.filter(ImageFilter.CONTOUR)
edgeF = imgF.filter(ImageFilter.FIND_EDGES)
imgF.show()
outF.show()
conF.show()
edgeF.show()
|
除此以外,ImageFilter模块还包括一些扩展性强的滤波器:
class PIL.ImageFilter.GaussianBlur(radius=2)
- Gaussian blur filter.
参数: radius – Blur radius. class PIL.ImageFilter.UnsharpMask(radius=2, percent=150, threshold=3)
- Unsharp mask filter.
See Wikipedia’s entry on digital unsharp masking for an explanation of the parameters.
- class PIL.ImageFilter.Kernel(size, kernel, scale=None, offset=0)
- Create a convolution kernel. The current version only supports 3×3 and 5×5 integer and floating point kernels.
In the current version, kernels can only be applied to “L” and “RGB” images.
参数: - size – Kernel size, given as (width, height). In the current version, this must be (3,3) or (5,5).
- kernel – A sequence containing kernel weights.
- scale – Scale factor. If given, the result for each pixel is divided by this value. the default is the sum of the kernel weights.
- offset – Offset. If given, this value is added to the result, after it has been divided by the scale factor.
- class PIL.ImageFilter.RankFilter(size, rank)
- Create a rank filter. The rank filter sorts all pixels in a window of the given size, and returns therank‘th value.
参数: - size – The kernel size, in pixels.
- rank – What pixel value to pick. Use 0 for a min filter, size * size / 2 for a median filter, size * size - 1 for a max filter, etc.
- class PIL.ImageFilter.MedianFilter(size=3)
- Create a median filter. Picks the median pixel value in a window with the given size.
参数: size – The kernel size, in pixels.
- class PIL.ImageFilter.MinFilter(size=3)
- Create a min filter. Picks the lowest pixel value in a window with the given size.
参数: size – The kernel size, in pixels.
- class PIL.ImageFilter.MaxFilter(size=3)
- Create a max filter. Picks the largest pixel value in a window with the given size.
参数: size – The kernel size, in pixels.
- class PIL.ImageFilter.ModeFilter(size=3)
- Create a mode filter. Picks the most frequent pixel value in a box
with the given size. Pixel values that occur only once or twice are
ignored; if no pixel value occurs more than twice, the original pixel
value is preserved.参数: size – The kernel size, in pixels. 更多详细内容可以参考:PIL/ImageFilter
9)图像增强
图像增强也是图像预处理中的一个基本技术,Pillow中的图像增强函数主要在ImageEnhance模块下,通过该模块可以调节图像的颜色、对比度和饱和度和锐化等:
imgE = Image.open("E:/photoshop/lena.jpg")
imgEH = ImageEnhance.Contrast(imgE)
imgEH.enhance(1.3).show("30% more contrast")
|
1
2
3
4
5
|
from PIL import ImageEnhance
imgE = Image.open("E:/photoshop/lena.jpg")
imgEH = ImageEnhance.Contrast(imgE)
imgEH.enhance(1.3).show("30% more contrast")
|
图像增强:
- class PIL.ImageEnhance.Color(image)
- Adjust image color balance.
This class can be used to adjust the colour balance of an image, in a manner similar to the controls on a colour TV set. An enhancement factor of 0.0 gives a black and white image. A factor of 1.0 gives the original image.
- class PIL.ImageEnhance.Contrast(image)
- Adjust image contrast.
This class can be used to control the contrast of an image, similar to the contrast control on a TV set. An enhancement factor of 0.0 gives a solid grey image. A factor of 1.0 gives the original image.
- class PIL.ImageEnhance.Brightness(image)
- Adjust image brightness.
This class can be used to control the brighntess of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
- class PIL.ImageEnhance.Sharpness(image)
- Adjust image sharpness.
This class can be used to adjust the sharpness of an image. An enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image.
图像增强的详细内容可以参考:PIL/ImageEnhance
除了以上介绍的内容外,Pillow还有很多强大的功能:
PIL.Image.alpha_composite(im1, im2)
PIL.Image.blend(im1, im2, alpha)
PIL.Image.composite(image1, image2, mask)
PIL.Image.eval(image, *args)
PIL.Image.fromarray(obj, mode=None)
PIL.Image.frombuffer(mode, size, data, decoder_name=’raw’, *args)
想了解更多,请参考:Image Module和 Pillow Reference
Python图像处理库Pillow入门的更多相关文章
- Python图像处理库Pillow常用使用方法
PIL(Python Imaging Library)是Python一个强大方便的图像处理库,只支持到Python2.7.Pillow是PIL的一个派生分支,在Python3中用Pillow代替PIL ...
- python图像处理库Pillow基本使用方法
安装pillow pillow的文档页面,documentation of Pillow 生成一个有单一颜色的图像 from PIL import Image, ImageDraw img = Ima ...
- python第三方库-图像处理库pillow
python图像处理库pillow 安装 pip install pillow 使用 导入 from PIL import pillow 读取图像 picture = Image.open('test ...
- Python图像处理库:Pillow 初级教程
Python图像处理库:Pillow 初级教程 2014-09-14 翻译 http://pillow.readthedocs.org/en/latest/handbook/tutorial.html ...
- Python 数据处理库 pandas 入门教程
Python 数据处理库 pandas 入门教程2018/04/17 · 工具与框架 · Pandas, Python 原文出处: 强波的技术博客 pandas是一个Python语言的软件包,在我们使 ...
- Python图像处理库:PIL中Image,ImageDraw等基本模块介绍
Python图像处理库:PIL中Image,ImageDraw等基本模块介绍 标签: 图像处理PILPYTHON 2016-08-19 10:58 461人阅读 评论(0) 收藏 举报 分类: 其他 ...
- Python图像处理库PIL中图像格式转换(一)
在数字图像处理中,针对不同的图像格式有其特定的处理算法. 所以,在做图像处理之前,我们须要考虑清楚自己要基于哪种格式的图像进行算法设计及事实上现.本文基于这个需求.使用python中的图像处理库PIL ...
- Python图像处理库——PIL
PIL全称Python Image Library,是python官方的图像处理库,包含各种图像处理模块.Pillow是PIL的一个派生分支,包含与PIL相同的功能,并且更灵活.python3.0之后 ...
- Python图像处理库PIL中图像格式转换
o 在数字图像处理中,针对不同的图像格式有其特定的处理算法.所以,在做图像处理之前,我们需要考虑清楚自己要基于哪种格式的图像进行算法设计及其实现.本文基于这个需求,使用python中的图像处理库PIL ...
随机推荐
- 点滴积累【JS】---JQuery实现条形统计图,适用于选择题等统计
效果: 思路:前台JS实现动态数据效果,后台可以拼接字符串或者用JSON加载数据 代码: <%@ Page Language="C#" AutoEventWireup=&qu ...
- NGUI拖拽简介
挂上UIDragDropItem就可以实现拖拽,按钮监听Drop消息即可实现对拖放的监听. UIDragDropItem有一个Clone On Drag选项,勾上可以克隆,但会被ScrollView遮 ...
- atitit.词法分析原理 词法分析器 (Lexer)
atitit.词法分析原理 词法分析器 (Lexer) 1. 词法分析(英语:lexical analysis)1 2. :实现词法分析程序的常用途径:自动生成,手工生成.[1] 2 2.1. 词法分 ...
- PHPCMS V9数据库表结构分析
PHPCMS V9可以轻松承载百万级的访问数据,最大的功臣就是PHPCMS良好的数据库结构,在数据库的设计方面,一定是下足了功夫. 一般网站的信息量离这个级别相差甚远,但是了解学习一下PHPCMS ...
- thread_CountDownLatch同步计数器
CountDownLatch类是一个同步计数器,构造时传入int参数,该参数就是计数器的初始值,每调用一次countDown()方法,计数器减1,计数器大于0 时,await()方法会阻塞程序继续执行 ...
- python之pilow验证码
pilow的基本操作 """ Created on Fri Jun 1 12:36:38 2018 @author: Frank """ f ...
- myeclipse能启动tomcat但是用startup.bat无法启动
myeclipse能启动tomcat但是用startup.bat无法启动 这个问题困扰了我一天,把一天的周末时间白白花费了.各种百度,各种尝试都没办法解决.在江湖上闯,难道就只有百度一招吗? 不是,我 ...
- C# tif文件转jpg
需要添加WindowBase,PresentationCore的引用. 代码如下: private Stream GetImageStream() { //可以通过网络或本地文件的形式,返回Tif文件 ...
- codeForces 574b Bear and Three Musketeers
一种巧妙到暴力方式,这题到抽象化:在一个无向图中,找一个度数和最小到三阶到圈. 首先对边进行枚举,这样确定了两个顶点,然后在对点进行枚举,找到一个可以构成三元圈到点,则计算他们到度数和. 最后保存最小 ...
- hdu6035 Colorful Tree 树形dp 给定一棵树,每个节点有一个颜色值。定义每条路径的值为经过的节点的不同颜色数。求所有路径的值和。
/** 题目:hdu6035 Colorful Tree 链接:http://acm.hdu.edu.cn/showproblem.php?pid=6035 题意:给定一棵树,每个节点有一个颜色值.定 ...