`
hereson
  • 浏览: 1427821 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

Python图像处理库:PIL中Image,ImageDraw等基本模块介绍

 
阅读更多

常用操作


合成 Image.blend(i1,i2,a)/Image.composite(i1,i2,mask)

缩略图 thumbnail(size,filter=None)  
Modifies in-place,Preserves aspect ratio
>>> myImage.thumbnail ((128, 128), Image.ANTIALIAS)
剪切 crop(bbox)

>>> bounds = (100, 100, 400, 400)
>>> cutoutIm = myImage.crop (bounds)
粘贴 paste(i2,where,mask=None)/paste(color,box=None,mask=None)

旋转 rotate(theta)
rotated around its center

翻转旋转 transpose(method)
ROTATE_90/180/270(clockwise), FLIP_TOP_BOTTOM(horizontal), FLIP_RIGHT_LEFT(vertical)
>>> fixedIm = myImage.transpose (ROTATE_90)

 

The Image Module


The Image module provides

  • a class with the same name which is used to represent a PIL image.
  • The module also provides a number of factory functions(including functions to load images from files, and to create new images)

图像对象 Image – from file or newly created

所有的图片操作必须有一个操作对象,例如Pil提供open(filename)进行这个过程,此后,一切关于图片的操作均基于这个对象。有以下几种创建image对象的方式:

1 Image.open(f)

>>> import Image
>>>
>>> Im = Image.open("lena.jpg")
>>> print Im.mode,Im.size,Im.format
RGB (256, 256) JPEG
>>> Im.show()

lena

如果文件不能打开,会抛出IOError异常。

可以查看image对象的format,mode,size,palette,info几个属性。

调用im.show()会在图片查看工具中显示当前操作的image对象。

标准版本的show方法的实现不太高效,因为它先把image保存到一个临时文件,然后调用xy工具来显示图像。如果你没有安装xy,那么它就无法工作了。不过如果它可以工作,倒还是非常方便用来debug和测试。

2 Image.new(mode,size,color=None)

color的默认值是黑色,这里我们新建一个红色的图像。

>>> newIm = Image.new (“RGBA”, (640, 480), (255, 0, 0)) #新建一个image对象creating images from scratch

3 Image.blend(i1,i2,a)  -- (p1 x (1 - a) + p2 x a)

选一张灰度图(L)做背景,和雷娜图(RGB)做blend操作

background1

>>> Im2 = Image.open("background.jpg").convert(Im.mode)
>>> Im2 = Im2.resize(Im.size)
>>> Im2.show()
>>>
>>> img = Image.blend(Im,Im2,0.2)
>>> img.show()

 tmpmprtrp

操作完毕后save(filename)用以保存这个临时的image对象img到硬盘。

4 Image.composite(i1,i2,mask)   --equal-sized images i1 ,i2 and mask("1", "L", or "RGBA") (p1 x (1 - m) + p2 x m)

5 Image.eval(f,i)  -- applying a function f to each pixel of image i

6 Image.merge(mode,bandList)  --Creates a multi-band image from a sequence of single-band images of equal size

以下是Image对象的全部方法:

save(f,format=None) 保存 如果f是一个file对象,必须指定format(format codes)
convert(mode) 转换mode  
copy()    
crop(bbox) 剪切 原图中bbox区域
filter(name) 滤镜 the name of predefined image enhancement filters
滤镜名字需要import ImageFilter
getbands() 通道的字符串序列 如RGB图返回('R', 'G', 'B')
getbbox() 包含非零区域的最小bbox  
getextrema() 最大最小像素点值 min&max pixel value
单通道图:返回元组(min,max)
多通道图:返回各个通道的元组组成的元组
getpixel(xy) 取像素点值 坐标xy处的pixel value or a sequence of pixel values
histogram(mask=None)

统计直方图

单通道图:返回列表[c0, c1, ...],ci是值为i的像素数

多通道图:a single sequence that is the concatenation of the sequences for all bands

mask参数:a same-sized mask image of mode "1" or "L"(include only those pixels correspond to nonzero pixels in the mask argument)

offset(dx,dy=None)

平移

Returns a new image the same size as the original, but with all pixels rotated dx in the +x direction,and dy in the +y direction.

If dy is omitted, it defaults to the same value as dx.

paste(i2,where,mask=None) 粘贴图片 where参数可以是
1 (x,y)坐标对:i2的像素点(0,0)对齐原图中的(x,y)粘贴,i2超过原图边界的部分被抛弃
2 bbox:i2必须和该bounding box大小一致
3 None:i2必须和原图大小一致
如果i2的mode和原图不一致,粘贴前会被转换。
mask参数:a same-sized mask image of mode "1","L" or “RGBA ”(control which pixels get replaced)
paste(color,box=None,mask=None) 填充颜色 如果box省略,整个图被填充为color色;mask参数同上
point(function) 改变像素点(函数) Returns a new image with each pixel modified.
point(table) 改变像素点(查表) To translate pixels using a table(a sequence of 256n values, where n is the number of bands in the image) lookup
putalpha(band)

改变alpha通道

The pixels of the band image(same-sized,"L" or "1") replace the alpha band(A) of the original image(RGBA) in place.

putpixel(xy, color) 改变单个像素点颜色 Note that this method is relatively slow. For more extensive changes, use paste or theImageDraw module instead.
resize(size,filter=None) 调整大小  
rotate(theta)

旋转(围绕图片中心)

 

Any pixels that are not covered by rotation of the original image are set to black.

show()

显示图片

On Unix systems, this method runs the xv image viewer to display the image. 
On Windows boxes,the image is saved in BMP format and can be viewed using Paint. 
This can be useful for debugging.

split()

分离通道

返回各个通道的灰度图组成的元组
Returns a tuple containing each band of the original image as an image of mode "L". 
For example, applying this method to an "RGB" image produces a tuple of three images, one each for the red, green, and blue bands.

thumbnail(size,filter=None) 缩略图 Modifies in-place,Preserves aspect ratio
transform(xs, ys, Image.EXTENT, (x0,y0,x1,y1))  

Returns a transformed copy of the image. In the transformed image, the point originally at (x0,y0) will appear at (0,0), and point (x1,y1) will appear at (xs, ys).

transform(xs, ys, Image.AFFINE, (a,b,c,d,e,f)) affine变换

The values a through f are the first two rows of an affine transform matrix.
Each pixel at (x,y) in the resulting image comes from position (ax+by+c,dx+ey+f) in the input
image, rounded to the nearest pixel.

transpose(method) 翻转旋转 ROTATE_90/180/270(clockwise), FLIP_TOP_BOTTOM(horizontal), FLIP_RIGHT_LEFT(vertical)

 

The ImageDraw Module


支持2D图像 The ImageDraw module provide basic 2D graphics support for Image objects.
It can for example be used to

  • create new images,
  • annotate or retouch existing images, and to generate graphics on the fly for web use.

For a more advanced drawing library for PIL, see The aggdraw Module.

创建绘画对象 ImageDraw module creates drawing surface for image

import Image, ImageDraw
im = Image.open(“vacation.jpeg") 
drawSurface = ImageDraw.Draw(im)

基本绘画操作 Basic methods of drawing surface

  • 弧/弦/扇形 chord arc pieslice (bbox, strtAng, endAng)
  • 椭圆 ellipse (bbox)
  • 线段/多段线 line (L)  draw.line(((60,60),(90,60), (90,90), (60,90), (60,60))) #draw a square
  • 点 point (xy)  #单像素点很小看不清,实际中可用实心小圆代替
  • 多边形 polygon (L) draw.polygon([(60,60), (90,60), (90,90), (60,90)]) #draw a square
  • 矩形 rectangle (bbox)       # first coord属于矩形, second coord不属于
  • 文字 text(xy,message,font=None) 绘制文字message,文本区域左上角坐标为xy
          drawable.text((10, 10), "Hello", fill=(255,0,0), font=None)
  • 文字大小 textsize(message,font=None)  给定文字message,返回所占像素(width,height)

可选参数 Common optional args for these methods

  • fill=fillColor
  • outline=outlineColor

矢量字体支持 TrueType Font support

import ImageFont
ttFont = ImageFont.truetype (“arial.ttf”, 16)
drawable.text ((10, 10), “Hello”, fill=(255,0,0), font=ttFont)

例子:Draw a Grey Cross Over an Image

复制代码
import Image, ImageDraw im = Image.open("lena.pgm") # Creates an object that can be used to draw in the given image.
draw = ImageDraw.Draw(im) # draw.line(xy, options) => Draws a line between the coordinates in the xy list.

# The coordinate list can be any sequence object containing either 2-tuples [ (x, y), ... ] # or numeric values [ x, y, ... ]. # The fill option gives the color to use for the line.
draw.line((0, 0) + im.size, fill=128) draw.line((0, im.size[1], im.size[0], 0), fill=128) del draw # write to stdout
im.save(sys.stdout, "PNG")
复制代码

 

The ImageChops module


a number of arithmetical image operations, called channel operations ("chops" 通道操作).

These can be used for various purposes, including special effects 特殊效果, image compositions 图像合成, algorithmic painting 算法绘画, and more.

At this time, channel operations are only implemented for 8-bit images (e.g. "L" and "RGB").

例子:比较两幅图像

Exact Comparison:

The quickest way to determine if two images have exactly the same contents is to get the difference between the two images, and then calculate the bounding box of the non-zero regions in this image. If the images are identical, all pixels in the difference image are zero, and the bounding box function returns None.

import ImageChops def equal(im1, im2): return ImageChops.difference(im1, im2).getbbox() is None

To get a measure of how similar two images are, you can calculate the root-mean-square (RMS) value of the difference between the images. If the images are exactly identical, this value is zero. The following function uses the difference function, and then calculates the RMS value from the histogram of the resulting image.

RMS Difference:

To get a measure of how similar two images are, you can calculate the root-mean-square (RMS) value of the difference between the images. If the images are exactly identical, this value is zero. The following function uses the difference function, and then calculates the RMS value from the histogram of the resulting image.

复制代码
# Example: File: imagediff.py

import ImageChops import math, operator def rmsdiff(im1, im2): "Calculate the root-mean-square difference between two images" h = ImageChops.difference(im1, im2).histogram() # calculate rms
    return math.sqrt(reduce(operator.add, map(lambda h, i: h*(i**2), h, range(256)) ) / (float(im1.size[0]) * im1.size[1]))
复制代码
分享到:
评论

相关推荐

    Python图像处理库PIL的ImageDraw模块介绍详解

    ImageDraw模块提供了图像对象的简单2D绘制。用户可以使用这个模块创建新的图像,注释或润饰已存在图像,为web应用实时产生各种图形。 PIL中一个更高级绘图库见The aggdraw Module 一、ImageDraw模块的概念 1、 ...

    解决Python3用PIL的ImageFont输出中文乱码的问题

    from PIL import Image, ImageDraw, ImageFont image= Image.new('RGB', (559, 320),(255,255,255)) draw = ImageDraw.Draw(image) # draw.text() font = ImageFont.truetype("arial", 40, encoding="unic") # 设置...

    img.pyPython使用PIL生成随机中文验证码

    from PIL import Image,ImageDraw,ImageFont,ImageFilter import random

    python PIL模块与随机生成中文验证码

    在这之前,你首先得了解Python中的PIL库。PIL是Python Imaging Library的简称,PIL是一...在PIL库中,最常用的模块有Image,ImageDraw,ImageEnhance,ImageFile等。 PIL的下载地址为:http://www.pythonware.com/prod

    Python实现图片添加文字

    需要使用的Python的图像库:PIL.更加详细的知识点如下: Imaga模块:用来创建,打开,保存图片文件 new(path):用来创建一个新的图片文件.该文件位于path所在的路径中。。打开后返回Image类型的图片。 open(path):...

    python给图片增加透明文字水印

    要给图片增加透明文字水印,可以...具体实现将取决于您选择的图像处理库和编程语言,以及对水印样式和位置的需求。在实际编写代码时,需要根据具体情况选择合适的库函数和方法,并进行适当的参数设置和图像处理操作。

    Python使用PIL库实现验证码图片的方法

    本文实例讲述了Python使用PIL库实现验证码图片的方法。分享给大家供大家参考,具体如下: 现在的网页中,为了防止机器人提交表单,图片验证码是很常见的应对手段之一。这里就不详细介绍了,相信大家都遇到过。 现在...

    python ImageDraw类实现几何图形的绘制与文字的绘制

    python PIL图像处理模块中的ImageDraw类支持各种几何图形的绘制和文本的绘制,如直线、椭圆、弧、弦、多边形以及文字等。 下面直接通过示例来进行说明: #-*- coding: UTF-8 -*- import numpy as np from PIL ...

    Python利用Pillow(PIL)库实现验证码图片的全过程

    前言 Pillow库有很多用途,本文使用Pillow来生成随机的验证码图片。 ...验证码是随机的,使用Python内置的random库来生成随机的颜色和随机...from PIL import Image, ImageDraw, ImageFont width, height, font_size, font

    利用Python如何生成便签图片详解

    前言 ...from PIL import Image, ImageDraw, ImageFont # get an image base = Image.open('Pillow/Tests/images/hopper.png').convert('RGBA') # make a blank image for the text, initialized to t

    python使用pil生成图片验证码的方法

    本文实例讲述了python使用pil生成图片验证码的方法。分享给大家供大家参考。具体实现方法如下: # -*- coding: utf-8 -*- #导入三个模块 import Image,ImageDraw,ImageFont import random import math '''基本功能'...

    利用Python自带PIL库扩展图片大小给图片加文字描述的方法示例

    只好选择使用Python PIL函数库对照片进行处理,利用Python自带的PIL库扩展图片大小给图片加上文字描述,大多都是库函数调用,只是给定图片宽度后计算文字所需行数的代码需要写。 代码比较丑,but it works. 代码示例...

    Python OpenCV实现图片上输出中文

    在Python中,可以借助PIL(Python Imaging Library)模块实现,相对简单很多,需要做的只是对图像进行OpenCV格式和PIL格式的相互转换。 # -*- coding: utf-8 -*- import cv2 import numpy from PIL import Image, ...

    python-pil-metaballs:一个与 PythonPIL 配合使用的元球系统

    python-pil-metaballs 这是基于上的代码,实际上大量借用了发布在那里的代码。 我进行了一些修改/改进以解决渲染在某些条件下会锁定的一些问题。... from PIL import Image , ImageDraw from metaballs im

    Python简单的制作图片验证码实例

    Python第三方库无比强大,PIL 是python的一个d第三方图片处理模块,我们也可以使用它来生成图片验证码 PIL安装 命令安装: pip install pillow 下载源码安装: 复制地址 :...

    python3生成图片,Python3生成图片源码下载

    Python3如何生成纯色图片,Python3生成图片源码分享 随机生成颜色,然后生成纯色图片源码 Python PIL库使用教程。ImageDraw,Image,ImageFont,ImageFilter

    python 实现PIL模块在图片画线写字

    from PIL import Image,ImageDraw im = Image.open(th.png) draw = ImageDraw.Draw(im) #实例化一个对象 draw.line((0, 0) + im.size, fill=128, width=5) #线的起点和终点,线宽 draw.line((0, im.size[1], im.size...

    python将文本转换成图片输出的方法

    from PIL import Image,ImageFont,ImageDraw text = u'欢迎访问软件开发网,//www.jb51.net' font = ImageFont.truetype("msyh.ttf",18) lines = [] line ='' for word in text.split(): print word if font.get...

Global site tag (gtag.js) - Google Analytics