python-PIL图像处理库

概述

PIL

Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,API非常简单易用。

PIL默认仅支持到Python2.7

Pillow

Pillow 与 PIL 几乎兼容,并且加入更多的新特性,支持Python3.x版本

英文文档:
http://code.nabla.net/doc/PIL/api/PIL.html

安装

pip install Pillow

导入包

from PIL import Image

常用模块说明

  • Image:对于图像的各种操作

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

  • ImageOps

打开图像

Image.open(path)

例子

from PIL import Image

# 打开一个jpg图像文件,注意路径要改成你自己的:
im = Image.open('test.jpg')

图片信息

  • Image.format:图像文件格式(后缀)
  • im.size:(width,height)
  • Image.mode:像素格式 RGB

例子

from PIL import Image
im = Image.open('test.jpg')
# 获得图像尺寸:
w, h = im.size

模式

1             1位像素,黑和白,存成8位的像素
L             8位像素,黑白
P             8位像素,使用调色板映射到任何其他模式
RGB           3×8位像素,真彩
RGBA          4×8位像素,真彩+透明通道
CMYK          4×8位像素,颜色隔离
YCbCr         3×8位像素,彩色视频格式
I             32位整型像素
F             32位浮点型像素

转换图片模式

转成灰度图

from PIL import Image
im = Image.open('test.jpg')
im = image.convert('L')

缩放图

语法

img=img.resize((width, height),Image.ANTIALIAS)

修改之后一定要赋给变量,否则无效

参数:
  • (width, height):tuple类型,图片大小
  • 参数2:图片质量
    • Image.NEAREST:低质量
    • Image.BILINEAR:双线性
    • Image.BICUBIC :三次样条插值
    • Image.ANTIALIAS:高质量

例子

将某个路径下的所有图片都缩小一半,并 保存替换原图片

import glob,os.path
from PIL import Image

path=r"C:\Users\mym\Desktop\color_clothing\*.*"
imgpaths=glob.glob(path)
img_num=len(imgpaths)
print(img_num)

for imgpath in imgpaths:
    img=Image.open(imgpath)
    size=img.size
    mode=img.mode
    newwidth=int(size[0]*0.5)
    newheight=int(size[1]*0.5)
    try:
        # 修改之后一定要赋给变量,否则无效
        img=img.resize((newwidth, newheight),Image.ANTIALIAS)
        img.save(imgpath)
    except:
        print("错误::",imgpath)

缩略图

im.thumbnail()

例子

from PIL import Image
im = Image.open('test.jpg')
# 获得图像尺寸:
w, h = im.size
# 缩放到50%:
im.thumbnail((w//2, h//2))

保存图片

im.save()

from PIL import Image
im = Image.open('test.jpg')
# 获得图像尺寸:
w, h = im.size
# 缩放到50%:
im.thumbnail((w//2, h//2))
# 把缩放后的图像用jpeg格式保存:
im.save('blur.jpg', 'jpeg')

原文出处:/show_1EF4SZ2puLMz.html