资讯详情

Python图像库Pillow (PIL) 入门

文章目录

  • 简介
  • 安装
  • 测试图像
  • 初试
  • 读写图像
    • 转换格式
    • 创建缩略图
  • 剪切、粘贴和合并图像
    • 复制子区域
    • 粘贴图像
    • 滚动图像
    • 分割和合并波段
  • 几何变换
    • 调整大小
    • 旋转
    • 转置
  • 颜色转换
    • 模式转换
  • 图像增强
    • 过滤器
    • 点运算
    • 处理单个波段
    • 增强高级图像
  • 图像序列
    • 读取序列
    • 迭代器
  • 图像打印
  • 读取方式
    • 上下文管理器
    • 文件类对象
    • 二进制数据
    • 从tar文件中读取
  • 解码器
    • 以draft模式读取
  • 官方示例程序
  • Image——PIL图像
  • ImageChops——通道编辑
  • ImageCms——配色文件
  • ImageColor——CSS3转RGB
  • ImageDraw——绘图
  • ImageEnhance——图像增强
  • ImageFile——图像打开和保存函数
  • ImageFilter——过滤器
  • ImageFont——字体
  • ImageGrab——复制屏幕或剪贴板内容
  • ImageMath——计算图像表达式
  • ImageMorph——形态学操作
  • ImageOps——预设图像处理操作
  • ImagePalette——调色板
  • ImagePath——二维向量数据的存储和操作
  • ImageQt——Qt支持
  • ImageSequence——遍历动图
  • ImageShow——显示图像
  • ImageStat——统计信息
  • ImageTk——Tkinter支持
  • ImageWin——Windows在上面创建和显示图像
  • ExifTags——EXIF标记
  • TiffTags——标准TIFF元数据
  • JpegPresets——JPEG质量设置
  • PSDraw——打印支持
  • PixelAccess——访问像素级图像数据
  • PyAccess——PixelAccess类的CFFI/Python实现
  • features——可用于检测系统Pillow特性
  • TODO:更多内容
  • 常用脚本
  • 参考文献

简介

PIL 是公认的 Python 图像处理标准库,在 Python 2.7 不再支持。

Pillow 是基于 PIL 模块 fork 主要用于分支。

Pillow 特性:

  • 支持多种文件格式
  • 高效内部表示
  • 图像处理能力强

Pillow 功能:

  • 图像归档
    • 创建缩略图
    • 转换文件格式
    • 打印图像
  • 图像显示
    • 提供 GUI 工具包如 Tk.PhotoImageBitmapImage 和 Windows的 ImageWin 接口
    • 提供 show() 方法显示图像,便于调试
  • 图像处理
    • 基本的图像处理功能,如卷积核过滤、色空间转换等
    • 调整图像调整、旋转和仿射变换
    • 直方图提取统计数据,可用于增强对比度和全局统计分析

安装

pip install Pillow 

本文版本如下:Pillow==8.2.0

测试图像

Lena,瑞典模特出生于1951年。这幅画出版于 1972 年度杂志《花花公子》分辨率为512×512,常被用于数字图像处理的各种实验。

test.jpg Leonardo,出生于1974年,美国演员。该图出自 2013 年电影《伟大的盖茨比》。

test.gif

初试

加载和显示图像,输出基本信息

from PIL import Image  im = Image.open('test.jpg') im.show()  # 打开默认看图软件 print(im.format)  # 格式 print(im.size)  # 大小或像素大小为(宽, 高) print(im.mode) # 模式,定义图像的通道,如L灰度模式 RGB真彩色模式 CMYK印刷四色模式
# JPEG
# (512, 512)
# RGB

读写图像

转换格式

将.jpg转换为.png,调用 Image.save()

from PIL import Image

with Image.open('test.jpg') as im:
    im.save('test.png')

创建缩略图

Image.thumbnail()

from PIL import Image

size = (128, 128)
with Image.open('test.jpg') as im:
    im.thumbnail(size)
    im.save('thumbnail.jpg')

效果

剪切、粘贴和合并图像

复制子区域

Image.crop()

from PIL import Image

im = Image.open('test.jpg')
box = (100, 100, 400, 400)  # 坐标为(左、上、右、下),即左上角和右下角坐标
crop = im.crop(box)
crop.save('crop.jpg')

效果

超过该尺寸的范围将填充为黑色

粘贴图像

Image.paste()

from PIL import Image

im = Image.open('test.jpg')
box = (100, 100, 400, 400)  # 坐标为(左、上、右、下),即左上角和右下角坐标
crop = im.crop(box)
crop = crop.transpose(Image.ROTATE_180)  # 逆时针旋转180度粘贴回去
im.paste(crop, box)
im.save('paste.jpg')

效果

滚动图像

from PIL import Image


def roll(image, delta):
    """滚动图像"""
    image = image.copy()
    xsize, ysize = image.size
    delta = delta % xsize
    if delta == 0:
        return image
    part1 = image.crop((0, 0, delta, ysize))
    part2 = image.crop((delta, 0, xsize, ysize))
    image.paste(part1, (xsize - delta, 0, xsize, ysize))
    image.paste(part2, (0, 0, xsize - delta, ysize))
    return image


im = Image.open('test.jpg')
im = roll(im, 200)
im.save('roll.jpg')

效果 Image.paste() 方法可以用透明度作为参数,取值0-255,0为全透明

分割和合并波段

Image.split()

Image.merge()

将 RGB 变为 BGR(OpenCV读取图像的默认模式)

from PIL import Image

im = Image.open('test.jpg')
r, g, b = im.split()
im = Image.merge('RGB', (b, g, r))
im.save('split_merge.jpg')

效果

波段:图像中的图层,例如卫星图像或数字照片中的图像 通道:计算机屏幕上显示图像的不同颜色或光,在Photoshop中经常出现 实际上是一样东西

几何变换

调整大小

Image.resize()

from PIL import Image

im = Image.open('test.jpg')
resize = im.resize((100, 100))
resize.save('resize.jpg')

效果

等比缩放

from PIL import Image


def scale(filePath, width=None, height=None):
    """指定宽或高,得到按比例缩放后的宽高 :param filePath: 图片路径 :param width: 目标宽度 :param height: 目标高度 :return: 按比例缩放后的宽和高 """
    if not width and not height:
        width, height = Image.open(filePath).size  # 原图片宽高
    if not width or not height:
        _width, _height = Image.open(filePath).size
        height = width * _height / _width if width else height
        width = height * _width / _height if height else width
    return int(width), int(height)


print(scale('test.jpg'))  # (512, 512)
print(scale('test.jpg', width=123, height=456))  # (123, 456)
print(scale('test.jpg', width=100))  # (100, 100)
print(scale('test.jpg', height=100))  # (100, 100)

width height = width ′ height ′ \frac{\text{width}}{\text{height}}=\frac{\text{width}^{'}}{\text{height}^{'}} heightwidth​=height′width′​ width ′ = height ′ height × width \text{width}^{'}=\frac{\text{height}^{'}}{\text{height}}\times \text{width} width′=heightheight′​×width height ′ = width ′ width × height \text{height}^{'}=\frac{\text{width}^{'}}{\text{width}}\times \text{height} height′=widthwidth′​×height

旋转

Image.rotate()

from PIL import Image

im = Image.open('test.jpg')
rotate = im.rotate(45)  # 逆时针旋转
rotate.save('rotate.jpg')

效果

将图像旋转90度,可以用 Image.rotate()Image.transpose()

转置

Image.transpose()

from PIL import Image

im = Image.open('test.jpg')
flip_left_right = im.transpose(Image.FLIP_LEFT_RIGHT)  # 水平翻转
flip_top_bottom = im.transpose(Image.FLIP_TOP_BOTTOM)  # 垂直翻转
rotate_90 = im.transpose(Image.ROTATE_90)  # 逆时针旋转90度
rotate_180 = im.transpose(Image.ROTATE_180)  # 逆时针旋转180度
rotate_270 = im.transpose(Image.ROTATE_270)  # 逆时针旋转270度
flip_left_right.save('flip_left_right.jpg')
flip_top_bottom.save('flip_top_bottom.jpg')
rotate_90.save('rotate_90.jpg')
rotate_180.save('rotate_180.jpg')
rotate_270.save('rotate_270.jpg')

效果

原图 水平翻转 垂直翻转 逆时针旋转90度 逆时针旋转180度 逆时针旋转270度

更通用的图像变换是调用 Image.transform()

颜色转换

模式转换

Image.convert()

from PIL import Image

im = Image.open('test.jpg')
convert = im.convert('L')  # 灰度模式
convert.save('convert.jpg')

效果

图像增强

过滤器

PIL.ImageFilter 提供了一批预设过滤器

from PIL import Image
from PIL import ImageFilter

im = Image.open('test.jpg')
blur = im.filter(ImageFilter.BLUR)  # 模糊
contour = im.filter(ImageFilter.CONTOUR)  # 轮廓
detail = im.filter(ImageFilter.DETAIL)  # 细节
edge_enhance = im.filter(ImageFilter.EDGE_ENHANCE)  # 边缘增强
edge_enhance_more = im.filter(ImageFilter.EDGE_ENHANCE_MORE)  # 边缘增强加强版
emboss = im.filter(ImageFilter.EMBOSS)  # 浮雕
find_edges = im.filter(ImageFilter.FIND_EDGES)  # 查找边缘
sharpen = im.filter(ImageFilter.SHARPEN)  # 锐化
smooth = im.filter(ImageFilter.SMOOTH)  # 平滑
smooth_more = im.filter(ImageFilter.SMOOTH_MORE)  # 平滑加强版
blur.save('blur.jpg')
contour.save('contour.jpg')
detail.save('detail.jpg')
edge_enhance.save('edge_enhance.jpg')
edge_enhance_more.save('edge_enhance_more.jpg')
emboss.save('emboss.jpg')
find_edges.save('find_edges.jpg')
sharpen.save('sharpen.jpg')
smooth.save('smooth.jpg')
smooth_more.save('smooth_more.jpg')

效果

原图 模糊 轮廓 细节 边缘增强 边缘增强加强版
原图 浮雕 查找边缘 锐化 平滑 平滑加强版

更多过滤器查阅 PIL.ImageFilter

点运算

Image.point() 用于转换图像像素值,如对比度操作

传入一个函数,每个像素都根据该函数进行处理

from PIL import Image

im = Image.open('test.jpg')
point = im.point(lambda i: i * 1.8)  # 每个像素值×1.8
point.save('point.jpg')

效果

处理单个波段

可以结合 Image.point()Image.paste() 来选择性修改图像

from PIL import Image

im = Image.open('test.jpg')
source = im.split()
R, G, B = 0, 1, 2
mask = source[R].point(lambda i: i > 100 and 255)  # 蒙版选择范围为红色波段大于100的
out = source[G].point(lambda i: i * 0.7)  # 绿色波段像素值×0.7
source[B].paste(out, None, mask)  # 绿色波段粘贴上述蒙版
im = Image.merge(im.mode, source)  # 构建一个新的多波段图像
im.save('multiband.jpg')

效果

高级图像增强

PIL.ImageEnhance 提供了高级图像增强,例如调整对比度、亮度、色彩平衡和锐度

from PIL import Image
from PIL import ImageEnhance

im = Image.open('test.jpg')
contrast = ImageEnhance.Contrast(im).enhance(1.3)  # 对比度
brightness = ImageEnhance.Brightness(im).enhance(1.5)  # 亮度
color = ImageEnhance.Color(im).enhance(0.7)  # 色彩平衡
sharpness = ImageEnhance.Sharpness(im).enhance(10.0)  # 锐度,0.0模糊,2.0锐化
contrast.save('contrast.jpg')
brightness.save('brightness.jpg')
color.save('color.jpg')
sharpness.save('sharpness.jpg')

效果

原图 对比度 亮度 色彩平衡 锐度

图像序列

Pillow 支持处理图像序列(动画格式),格式包括 FLI/FLC、GIF、TIFF 等

读取序列

Pillow 自动载入序列的第一帧,用 Image.seek()Image.tell() 方法在不同帧之间移动

from pathlib import Path

from PIL import Image

Path('./frames').mkdir(parents=True, exist_ok=True)  # 创建目录

im = Image.open('test.gif')
try:
    i = 1
    while True:
        im.seek(im.tell() + 1)  # 逐帧保存
        frame = im.convert('RGB')
        frame.save('./frames/{}.jpg'.format(i))
        i += 1
except EOFError:
    pass

效果

迭代器

ImageSequence.Iterator

from pathlib import Path

from PIL import Image
from PIL import ImageSequence

Path('./frames').mkdir(parents=True, exist_ok=True)  # 创建目录

im = Image.open('test.gif')
for i, frame in enumerate(ImageSequence.Iterator(im)):
    frame = im.convert('RGB')
    frame.save('./frames/{}.jpg'.format(i + 1))

效果同上

图像打印

Pillow 支持使用打印机语言 PostScript 打印图像、文本和图形

from PIL import Image
from PIL import PSDraw

im = Image.open('test.jpg')
title = 'Lena'
box = (1 * 72, 2 * 72, 7 * 72, 10 * 72)
ps = PSDraw.PSDraw()  # 默认为sys.stdout或sys.stdout.buffer
ps.begin_document(title)
ps.image(box, im, 75)  # 打印图像,分辨率为75dpi
ps.rectangle(box)
ps.setfont('HelveticaNarrow-Bold', 36)  # 打印标题
ps.text((3 * 72, 4 * 72), title)
ps.end_document()
# %!PS-Adobe-3.0
# save
# /showpage { } def
# %%EndComments
# %%BeginDocument
# /S { show } bind def
# /P { moveto show } bind def
# /M { moveto } bind def
# /X { 0 rmoveto } bind def
# /Y { 0 exch rmoveto } bind def
# /E { findfont
# dup maxlength dict begin
# { 
        
# 1 index /FID ne { def } { pop pop } ifelse
# } forall
# /Encoding exch def
# dup /FontName exch def

        标签: p20k3aqj圆形连接器

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台