import PIL (图像处理库)使用方法

PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。
from PIL import Image, ImageDraw

Image 对于图像的各种操作
ImageDraw 模块提供了图像对象的简单2D绘制。用户可以使用这个模块创建新的图像,注释或润饰已存在图像,为web应用实时产生各种图形。

读入图像数据

Image.read(path) 读入图片

图片信息

方法 功能
Image.format 图像文件格式(后缀)
im.size (width,height)
Image.mode 像素格式 RGB…

图片处理

方法 功能
Image.thumbnail((w//2, h//2)) 缩放
out = im.resize((128, 128)) 重定义大小
out = im.rotate(45) 旋转
im.filter(ImageFilter.BLUR) 模糊
Image.show() 显示图像(标准实现不是很有效率)不过测试可用
regionregion.transpose(Image.ROTATE_180) 旋转
box = (100, 100, 400, 400) region = im.crop(box) 获取子区域
Image.paste(region, box) 处理完子区域粘贴回去
r, g, b = im.split() 分离图像通道
im = Image.merge(“RGB”, (b, g, r)); 合并图像通道
Image.mode(‘/Users/michael/thumbnail.jpg’, ‘jpeg’) 保存
//读取图片并显示
from PIL import Image, ImageDraw
#指定路径
sample_image_path = os.path.join(RAW_DATA_DIR, 'normal_1/images/img_0.png')
#读入图片
sample_image = Image.open(sample_image_path)
print  sample_image.format, "%dx%d" % sample_image.size, sample_image.mode
#输出
plt.title('Sample Image')
plt.imshow(sample_image)
plt.show()
#图片格式转换
import os, sys
import Image

for infile in sys.argv[1:]:
    f, e = os.path.splitext(infile)
    outfile = f + ".jpg"
    if infile != outfile:
        try:
            Image.open(infile).save(outfile)
        except IOError:
            print "cannot convert", infile

ImageDraw

#给图像绘制一个矩形框
sample_image_roi = sample_image.copy()
fillcolor=(255,0,0)
draw = ImageDraw.Draw(sample_image_roi)
points = [(1,76), (1,135), (255,135), (255,76)]
for i in range(0, len(points), 1):
    draw.line([points[i], points[(i+1)%len(points)]], fill=fillcolor, width=3)
del draw  #删除变量

plt.title('Image with sample ROI')
plt.imshow(sample_image_roi)
plt.show()

参考文档

The Python Imaging Library Handbook

猜你喜欢

转载自blog.csdn.net/csdnhuaong/article/details/80511810