最近工作中有一些简单的图片处理的需求,记录一下学习过程。

一些概念
先了解一些概念
光栅图像
光栅图像(raster image),又叫位图,像素图,是一种展示数字图像的方式。在计算机图形学中,它采用点阵数据结构,存储为矩形的像素网格。光栅图像可以存储在不同格式的图像文件中,比如gif, jpg, bmp。
像素
像素的英文是pixel,这个单词由pix+el组成。英文中图片的复数是pictures,可以简写为pics,其中cs发音和x相近,最后成了pix。英文中元素的单词是element,取前面两个字母el,和pix组合就成了pixel,意为图像元素,简称为像素。
像素一般被认为是一个图像中的最小单位。每个像素不是一个点或者是一个方块,而是一个抽象的取样,仔细处理的话,一幅视频中的像素可以在任何尺度上看起来都不像分离的点或者方块;但是在很多情况下,它们采用点或者方块显示。
PIL
PIL是python中用于处理光栅图像的库。
Band
当我们在计算机屏幕上看到一个图像时,它看起来是二维的,但除了行和列的像素,图像也有层。这些层通常被称为Band或Channel。
彩色数字图像由像素组成,并且像素由通过一系列代码表示的原色的组合构成。在此上下文中的通道是与仅由这些原色之一构成的彩色图像相同大小的灰度图像。例如,来自标准数码相机的图像将具有红色,绿色和蓝色通道。灰度图像只有一个通道。
PIL将图层通道抽象为Band。图像可以有一个或多个band组成,PIL允许开发者在单个图像中存储多个波段,前提是它们都具有相同的尺寸和深度。举例来说,一张png图片会有'R','G','B','A'这4个band,分表对应红,绿,蓝,透明度这四个值。
可以使用getbands()方法来获取图片的band。比如
>>> txt = Image.new('RGBA', (255, 255), (255, 255, 255, 255))
>>> print txt.getbands()
('R', 'G', 'B', 'A')
Mode
图像的模式定义图像中像素的类型和深度,PIL中比较常用的有"RGBA"
操作实践
打开一张图片
>>> from PIL import Image
>>> file_path = '兄弟会.jpg'
>>> base = Image.open(file_path)
>>> base.size
(180, 180)
>>> base.show()

旋转
旋转180度,可以看到效果还不错
>>> base.transpose(Image.ROTATE_180).show()

旋转45度,失真很严重
>>> base.rotate(45).show()

切割
切一部分下来
>>> box = (40, 40, 120, 120)
>>> base.crop(box).show()

变灰
>>> base.convert('L').show()

画图
加点文字,采用苹方粗体
>>> pingfang_font = ImageFont.truetype(font='pingfang-sc-bold.ttf', size=20)
>>> txt = Image.new('RGBA', base.size, (255, 255, 255, 0))
>>> d = ImageDraw.Draw(txt)
>>> d.text((20, 5), u'胜利属于兄弟会!', fill=(255, 0, 34, 255), font=pingfang_font)
>>> Image.alpha_composite(base, txt).show()

先做一个thumbnail,然后用thumbnail给原图打上水印
>>> new_base = Image.open(file_path)
>>> base.thumbnail(size)
>>> new_base.paste(base, (90, 90))
>>> new_base.show()

模糊
使用PIL很容易实现简单高斯模糊效果。
>>> from PIL import ImageFilter
>>> base.filter(ImageFilter.GaussianBlur(1.0)).show()

总结
PIL挺有意思的,使用代码对图片进行处理,看着花花绿绿的结果,感觉自己好像魔术师一样。
当然,这个领域博大精深,以后有机会再探索。
网友评论