PIL(Python Imaging Library)-用Python画图

最近工作中需要用到图片的自动化处理,于是了解了一下PIL程序库。

什么是PIL

PIL(Python Imaging Library)是python中处理图像常用的一个库,常见的用法包括可以操作二维像素点、线、文字以及对现有图片的缩放、变形、通道处理,也可以转换图片的编码格式,可以比较两幅图片的不同。

安装

python中安装库一般通过pip或者easy_install,如果这两者不可行,一般在搜索引擎找到官网或者github项目地址,进入主目录执行python setup.py install。PIL安装方式亦如上所述。

使用场景

基本操作:打开,打印文件属性和展示图片

>>> import Image
>>> im = Image.open("lena.ppm")
>>> print im.format, im.size, im.mode
PPM (512, 512) RGB

>>> im.show()

其中format包括jpg,png,gif,bmp等
size很好理解,返回的是一个二元组代表宽高
mode代表的是色彩模式,除了RGB,共支持如下模式

  • 1 (1-bit pixels, black and white, stored with one pixel per byte)
  • L (8-bit pixels, black and white)
  • P (8-bit pixels, mapped to any other mode using a colour palette)
  • RGB (3x8-bit pixels, true colour)
  • RGBA (4x8-bit pixels, true colour with transparency mask)
  • CMYK (4x8-bit pixels, colour separation)
  • YCbCr (3x8-bit pixels, colour video format)
  • I (32-bit signed integer pixels)
  • F (32-bit floating point pixels)
图片缩放:
size = (128, 128)

im = Image.open(infile)
im.thumbnail(size)

经过测试,缩放是会保留原始长宽比的,缩放操作其实意味着在保留长宽比的前提下,缩放后结果的高不大于128,宽也不大于128.

缩放时还有一个filter参数,可以控制图片的质量,压缩时PIL处理过程中称为resampling的过程,可以采用以下filter:

- NEAREST
Pick the nearest pixel from the input image. Ignore all other input pixels.
直接采用该像素点最近的像素点的色彩值

- BILINEAR
Use linear interpolation over a 2x2 environment in the input image. Note that in the current version of PIL, this filter uses a fixed input environment when downsampling.
类似第一种,只不过扩大了采样的范围并作平均。是2*2的范围

- BICUBIC
Use cubic interpolation over a 4x4 environment in the input image. Note that in the current version of PIL, this filter uses a fixed input environment when downsampling.
进一步扩大到了4*4的范围

- ANTIALIAS
(New in PIL 1.1.3). Calculate the output pixel value using a high-quality resampling filter (a truncated sinc) on all pixels that may contribute to the output value. In the current version of PIL, this filter can only be used with the resize and thumbnail methods.
看不太懂,反正这个是推荐的,官方认为只要不是对速度有非常大的要求,都要采用这个filter。

通过实际操作,确实发现第四种明显减少了锯齿,而第一种nearest锯齿最为严重

PIL(Python Imaging Library)-用Python画图_第1张图片
对比ANTIALIAS vs NEAREST
图片转换:
im = Image.open(“a.png")
im.save(“a.jpg”)

PIL默认会读取后缀名来应该用何种编码来转换这张图片。

图片粘贴:
width = 850
height = 510
im = Image.open(“for_paste.jpg")
image = Image.new('RGB', (width, height), (255, 255, 255))
box = (250,42,550,325)

image.paste(im,box)

代码首先新建了一个image对象,作为我们的画布,然后将for_paster.jpg粘贴到画面中的区域。box是一个四元组,含义为(左上角x,左上角y,右下角x,右下角y)。这里如果box的宽和高与被粘贴图片的宽高不一致,系统会抛异常。

图片中写字:
#创建一个字体实例,采用微软雅黑38号
font_en = ImageFont.truetype('/Library/Fonts/Microsoft/Microsoft Yahei.ttf',38)
draw = ImageDraw.Draw(image)

#指定字体和颜色(RGB)
draw.text( (0,100), u’He acknowledged his faults.', font=font_en,fill=(0,0,0))
del draw

结果如下:

PIL(Python Imaging Library)-用Python画图_第2张图片
Python画图

你可能感兴趣的:(PIL(Python Imaging Library)-用Python画图)