Home  >  Article  >  Backend Development  >  How to use the Python image processing library PIL

How to use the Python image processing library PIL

王林
王林forward
2023-05-13 16:31:064584browse

1. Introduction

1. Basic introduction

Pillow is a relatively basic image processing library in Python. It is mainly used for basic image processing, such as cropping images, adjusting image sizes and images. Color processing, etc. Compared with Pillow, OpenCV and Scikit-image have richer functions and are therefore more complex to use. They are mainly used in fields such as machine vision and image analysis, such as the well-known "face recognition" application.

2. Features

  • Supports a wide range of formats

    Pillow supports a wide range of image formats, such as "jpeg", "png", "bmp", "gif", "ppm", "tiff" etc. At the same time, it also supports mutual conversion between image formats. In short, Pillow can process images in almost any format

  • Provides rich functions

    Pillow provides rich image processing functions, which can be summarized in two aspects:

    Image archiving includes creating thumbnails, generating preview images, image batch processing, etc.; while image processing includes resizing images, cropping images, pixel processing, adding filters, image color processing, etc.

    • Image archiving

    • Image processing

  • Used with GUI tools

3. Installation

pip install pillow
导包
imoprt PIL

2. Image object

1. Instantiation object

1.1 Instantiation

Guide package

from PIL import Image

Use the open method

im = PIL.Image.open(fp) # 导入图片
im.show() # 展示图片

fp: Picture path

Use the open method

im = Image.new(mode,size,color) # 创建图片
im.show() # 展示图片

The parameter description is as follows:

  • mode: image mode, string parameters, such as RGB (true color image), L (grayscale image), CMYK (color map printing mode), etc.

  • size: image size, tuple parameters (width, height) represent the pixel size of the image

  • color: image color, the default value is 0 for black, parameter value Supports (R,G,B) triplet number format, hexadecimal value of color and English word of color

1.2 Image mode

mode Description
1 1 bit pixel (value range 0-1), 0 means black ,1 means white,monochrome channel.
L 8-bit pixel (value range 0 -255), grayscale image, monochrome channel.
P 8-bit pixel, using palette mapping to any other mode, monochrome channel.
RGB 3 x 8-bit pixels, true color, three color channels, the value range of each channel is 0-255.
RGBA 4 x 8-bit pixels, true color, transparent channel, four color channels.
CMYK 4 x 8-bit pixels, four color channels, suitable for printing pictures.
YCbCr 3 x 8-bit pixels, color video format, three color channels.
LAB 3 x 8-bit pixels, L * a * b color space, three color channels
HSV 3 x 8-bit pixels, hue, saturation, value color space, three color channels.
I 32-bit signed integer pixel, monochrome channel.
F 32-bit floating point pixels, monochrome channel.

2、 对象属性

import PIL.Image

im = PIL.Image.open(r"D:\35005\Pictures\Screenshots\微信图片_20220302175157.jpg")
print(im.size) # 查看图片大小
print(im.readonly) # 查看是否为只读,1为是,0为否
print(im.format) # 查看图片的格式
print(im.info) # 查看图片的相关信息
print(im.mode) # 查看图片的模式

3、 格式转换

3.1 save 方法

save 方法用于保存 图像,当不指定文件格式时,它会以默认的图片格式来存储;如果指定图片格式,则会以指定的格式存储图片

语法:

im = PIL.Image.open(r"D:\35005\Pictures\Screenshots\微信图片_20220302175157.jpg")
im.save(fp, format=None) # 保存图片

参数说明如下:

  • fp:图片的存储路径,包含图片的名称,字符串格式

  • format:可选参数,可以指定图片的格式

3.2 convert 方法

注意,并非所有的图片格式都可以用 save() 方法转换完成,比如将 PNG 格式的图片保存为 JPG 格式,如果直接使用 save() 方法就会出现错误

引发错误的原因是由于 PNG 和 JPG 图像模式不一致导致的。其中 PNG 是四通道 RGBA 模式,即红色、绿色、蓝色、Alpha 透明色;JPG 是三通道 RGB 模式。因此要想实现图片格式的转换,就要将 PNG 转变为三通道 RGB 模式

Image 类提供的 convert() 方法可以实现图像模式的转换。该函数提供了多个参数,比如 mode、matrix、dither 等,其中最关键的参数是 mode,其余参数无须关心

语法:

im.convert(mode, params) # 转换模式
im.save(fp) # 保存图片

参数:

  • mode:指的是要转换成的图像模式

  • params:其他可选参数

4、 图片缩放

在图像处理过程中经常会遇到缩小或放大图像的情况,Image 类提供的 resize() 方法能够实现任意缩小和放大图像

语法:

im_new = im.resize(size, resample=image.BICUBIC, box=None, reducing_gap=None) # 注意要重新赋值
im_new.show() # 缩放后的图片

参数:

  • size:元组参数 (width,height),图片缩放后的尺寸

  • resample:可选参数,指图像重采样滤波器,与 thumbnail() 的 resample 参数类似,默认为 Image.BICUBIC

  • box:对指定图片区域进行缩放,box 的参数值是长度为 4 的像素坐标元组,即 (左,上,右下)。注意,被指定的区域必须在原图的范围内,如果超出范围就会报错。当不传该参数时,默认对整个原图进行缩放

    (0, 0, 120, 180)代表的是以原图的左上角为原点,选择宽和高分别是(120,180)的图像区域

  • reducing_gap:可选参数,浮点参数值,用于优化图片的缩放效果,常用参数值有 3.0 和 5.0

5、 创建缩略图

缩略图指的是将原图缩小至一个指定大小(size)的图像。通过创建缩略图可以使图像更易于展示和浏览

Image 对象提供了一个 thumbnail() 方法用来生图像的缩略图,等比缩放

语法:

im.thumbnail(size,resample) # 直接在原图的基础上修改
im.show() # 缩放后的图片

参数:

  • size:元组参数,指的是缩小后的图像大小

  • resample:可选参数,指图像重采样滤波器,有四种过滤方式,分别是 Image.BICUBIC(双立方插值法)、PIL.Image.NEAREST(最近邻插值法)、PIL.Image.BILINEAR(双线性插值法)、PIL.Image.LANCZOS(下采样过滤插值法),默认为 Image.BICUBIC

6、 图像分离与合并

图像(指数字图像)由许多像素点组成,像素是组成图像的基本单位,而每一个像素点又可以使用不同的颜色,最终呈现出了绚丽多彩的图像 ,而图像的分离与合并,指的就是图像颜色的分离和合并

6.1 split 方法

im = PIL.Image.open(r"D:\35005\Pictures\Screenshots\微信图片_20220302175157.jpg")
r, g, b = im.split() # split 方法使用较简单,分离通道
r.show()
g.show()
b.show()

6.2 merge 方法

Image 类提供的 merge() 方法可以实现图像的合并操作。注意,图像合并,可以是单个图像合并,也可以合并两个以上的图像

im_merge = PIL.Image.merge(mode, bands)
im_merge.show()

参数:

  • mode:指定输出图片的模式

  • bands:参数类型为元组或者列表序列,其元素值是组成图像的颜色通道,比如 RGB 分别代表三种颜色通道,可以表示为 (r, g, b)

6.3 blend 方法

Image 类也提供了 blend() 方法来混合 RGBA 模式的图片(PNG 格式)

语法:

PIL.Image.blend(image1,image2, alpha)

参数:

  • image1:图片对象1

  • image2:图片对象2

  • alpha:透明度 ,取值范围为 0 到 1,当取值为 0 时,输出图像相当于 image1 的拷贝,而取值为 1 时,则是 image2 的拷贝,只有当取值为 0.5 时,才为两个图像的中合。因此改值的大小决定了两个图像的混合程度

7、 图像处理

7.1 图像裁剪

Image 类提供的 crop() 函数允许我们以矩形区域的方式对原图像进行裁剪

语法:

im_crop = im.crop(box=None) # box 代表裁剪区域
im_crop.show()

box 是一个有四个数字的元组参数 (x_左上,y_左下,x1_右上,y1_右下),分别表示被裁剪矩形区域的左上角 x、y 坐标和右下角 x,y 坐标。默认 (0,0) 表示坐标原点,宽度的方向为 x 轴,高度的方向为 y 轴,每个像素点代表一个单位

7.2 拷贝和粘贴

拷贝、粘贴操作几乎是成对出现的,Image 类提供了 copy() 和 paste() 方法来实现图像的复制和粘贴

拷贝语法:

im_copy = im.copy() # 复制图片

粘贴语法:

im_copy.paste(image, box=None, mask=None)

参数:

  • image:指被粘贴的图片

  • box:指定图片被粘贴的位置或者区域,其参数值是长度为 2 或者 4 的元组序列,长度为 2 时,表示具体的某一点 (x, y);长度为 4 则表示图片粘贴的区域,此时区域的大小必须要和被粘贴的图像大小保持一致

  • mask:可选参数,为图片添加蒙版效果

注意:

  • 粘贴后的图片模式将自动保持一致,不需要进行额外的转换

from PIL import Image

im = Image.open(r"D:\35005\Pictures\Screenshots\微信图片_20220302175157.jpg")

# 复制一张图片副本
im_copy = im.copy()

# 对副本进行裁剪
im_crop = im_copy.crop((0, 0, 200, 100))

# 创建一个新的图像作为蒙版,L模式,单颜色值
image_new = Image.new('L', (200, 100), 200)

# 将裁剪后的副本粘贴至副本图像上,并添加蒙版
im_copy.paste(im_crop, (100, 100, 300, 200), mask=image_new)

# 显示粘贴后的图像
im_copy.show()

8、几何变化

图像的几何变换主要包括图像翻转、图像旋转和图像变换操作,Image 类提供了处理这些操作的函数 transpose()、rotate() 和 transform()

8.1 transpose

该函数可以实现图像的垂直、水平翻转

语法:

im_out = im.transpose(method) # 生成新的图像对象

method取值:

  • Image.FLIP_LEFT_RIGHT:左右水平翻转

  • Image.FLIP_TOP_BOTTOM:上下垂直翻转

  • Image.ROTATE_90:图像逆时针旋转 90 度

  • Image.ROTATE_180:图像旋转 180 度

  • Image.ROTATE_270:图像旋转 270 度

  • Image.TRANSPOSE:图像转置

  • Image.TRANSVERSE:图像横向翻转

8.2 rotate

当我们想把图像旋转任意角度时,可以使用 rotate() 函数

语法:

im_out = im.rotate(angle, resample=PIL.Image.NEAREST, expand=None, center=None, translate=None, fillcolor=None) # 返回图像对象

参数:

  • angle:表示任意旋转的角度

  • resample:重采样滤波器,默认为 PIL.Image.NEAREST 最近邻插值方法

  • expand:可选参数,表示是否对图像进行扩展,如果参数值为 True 则扩大输出图像,如果为 False 或者省略,则表示按原图像大小输出

  • center:可选参数,指定旋转中心,参数值是长度为 2 的元组,默认以图像中心进行旋转

  • translate:参数值为二元组,表示对旋转后的图像进行平移,以左上角为原点;translate的参数值可以为负数

  • fillcolor:可选参数,填充颜色,图像旋转后,对图像之外的区域进行填充

8.3 transform

该函数能够对图像进行变换操作,通过指定的变换方式,产生一张规定大小的新图像

语法:

im_out = im.transform(size, method, data=None, resample=0) # 返回图像对象

参数:

  • size:指定新图片的大小

  • method:指定图片的变化方式,比如 Image.EXTENT 表示矩形变换

  • data:该参数用来给变换方式提供所需数据

  • resample:图像重采样滤波器,默认参数值为 PIL.Image.NEAREST

三、 ImageFilter

1、 简介

随着数字图像技术的不断发展,图像降噪方法也日趋成熟,通过某些算法来构造滤波器是图像降噪的主要方式。滤波器能够有效抑制噪声的产生,并且不影响被处理图像的形状、大小以及原有的拓扑结构

Pillow 通过 ImageFilter 类达到图像降噪的目的,该类中集成了不同种类的滤波器,通过调用它们从而实现图像的平滑、锐化、边界增强等图像降噪操作

2. Noise reduction processing

2.1 Image noise reduction filter

##ImageFilter.GaussianBlur()Gaussian BlurImageFilter.UnsharpMask( )Unsharp Mask FilterImageFilter.Kernel()Convolution Kernel FilterImageFilter.MinFilter(size)Minimum filter selects the smallest pixel value from the area specified by the size parameter and stores it in the output image. ImageFilter.MedianFilter(size)Median filter selects the median pixel value from the area specified by the size parameter and stores it in the output image . ImageFilter.MaxFilter(size)Maximum filterImageFilter.ModeFilter()Pattern filtering

2.2 使用语法

语法:

im_ft = im.filter(filt_mode) # 返回图像对象,里面传入滤波器

实例:

from PIL import Image, ImageFilter

im = Image.open(r"D:\35005\Pictures\Screenshots\微信图片_20220302175157.jpg")
im_ft = im.filter(ImageFilter.EMBOSS) # 添加浮雕滤波器
im_ft.show()

相当于PS里面添加的滤镜

四、 ImageColor

1、 简介

Pillow 提供了颜色处理模块 ImageColor,该模块支持不同格式的颜色,比如 RGB 格式的颜色三元组、十六进制的颜色名称(#ff0000)以及颜色英文单词("red")。同时,它还可以将 CSS(层叠样式表,用来修饰网页)风格的颜色转换为 RGB 格式

在 ImageColor 模块对颜色的大小写并不敏感,比如 "Red" 也可以写为 " red"

2、 颜色处理

2.1 颜色命名

ImageColor 支持多种颜色模式的的命名(即使用固定的格式对颜值进行表示),比如我们熟知的 RGB 色彩模式,除此之外,还有 HSL (色调-饱和度-明度)、HSB (又称 HSV,色调-饱和度-亮度)色彩模式。下面对 HSL 做简单介绍:

  • H:即 Hue 色调,取值范围 0 -360,其中 0 表示“red”,120 表示 “green”,240 表示“blue”

  • S:即 Saturation 饱和度,代表色彩的纯度,取值 0~100%,其中 0 代表灰色(gry),100% 表示色光最饱和

  • L:即 Lightness 明度,取值为 0~100%,其中 0 表示“black”黑色,50% 表示正常颜色,100% 则表示白色

亮度和明度的表达方式类似,链接中有具体描述:【https://www.zhihu.com/question/22077462】

ImageColor 模块比较简单,只提供了两个常用方法,分别是 getrgb() 和 getcolor() 函数

2.2 getrgb

语法:

rgb = PIL.ImageColor.getrgb(color) # 得到颜色的 rgb 数值

color参数即可以是英文,也可以是HSL和HSB模式2.3

应用:

from PIL import Image, ImageColor

im = Image.new(mode="RGB", size=(100, 100), color=ImageColor.getrgb('HSL(0,100%,50%)'))
im.show()

2.3 getcolor

语法:

val = PIL.ImageColor.getcolor(color, mode)

参数:

  • color:一个颜色名称,字符串格式,可以是颜色的英文单词,或者十六进制颜色名。如果是不支持的颜色,会报 ValueError 错误

  • mode:指定色彩模式,如果是不支持的模式,会报 KeyError 错误

五、 ImageFont

1、 简介

ImageFont模块定义了相同名称的类,即ImageFont类。这个类的实例存储bitmap字体,用于ImageDraw类的text()方法

PIL使用自己的字体文件格式存储bitmap字体。用户可以使用pilfont工具包将BDF和PCF字体描述器(Xwindow字体格式)转换为这种格式

2、 模块函数

2.1 load

语法:

ft = PIL.ImageFont.load(font_file)

从指定的文件中加载一种字体 ,返回字体对象

2.2 load_path

语法:

ft = PIL.ImageFont.load_path(font_file)

和函数load()一样,但是如果没有指定当前路径的话,会从sys.path开始查找指定的字体文件

2.3 truetype

语法:

ft = PIL.ImageFont.truetype(file, size[, encoding=None])

参数:

  • file: 加载一个TrueType或者OpenType字体文件

  • size: 为指定大小的字体创建了字体对象

  • encoding:字体编码,主要字体编码有: “unic”(Unicode),“symb”(Microsoft Symbol),“ADOB”(Adobe Standard),“ADBE”(Adobe Expert)和“armn”(Apple Roman)

2.4 load_default

语法:

ft = PIL.ImageFont.load_default()

加载一个默认字体,返回一个字体对象

3、 模块方法

3.1 getsize

语法:

size = ft.getsize(text)

返回给定文本的宽度和高度,返回值为2元组

3.2 getmask

语法:

obj = ft.getmask(text,mode=None) # 为给定的文本返回一个位图。这个位图是PIL内部存储内存的实例

参数:

  • text :要渲染的文本。

  • mode:某些图形驱动程序使用它来指示驱动程序喜欢哪种模式;如果为空,渲染器可能返回任一模式。请注意,模式始终是字符串

六、 ImageDraw

1、 简介

1.1 导入

ImageDraw 模块也是 Pillow 库的主要模块之一,它能给图像化圆弧,画横线,写上文字等

导入:

from PIL import ImageDraw

实例化对象:

from PIL import Image, ImageDraw

im = Image.open("./a.jpg") # 创建 image 对象
draw = ImageDraw.Draw(im) # 实例化可以在指定图像上画图的 Draw 对象

1.2 基本概念

  • Coordinates

    • 绘图接口使用和PIL一样的坐标系统,即(0,0)为左上角。

  • Colours

    • 为了指定颜色,用户可以使用数字或者元组,对应用户使用函数Image.new或者Image.putpixel。对于模式为“1”,“L”和“I”的图像,使用整数。对于“RGB”图像,使用整数组成的3元组。对于“F”图像,使用整数或者浮点数。

    • 对于调色板图像(模式为“P”),使用整数作为颜色索引。在1.1.4及其以后,用户也可以使用RGB 3元组或者颜色名称。绘制层将自动分配颜色索引,只要用户不绘制多于256种颜色。

  • Colours Names

    • A、 十六进制颜色说明符,定义为“#rgb”或者“#rrggbb”。例如,“#ff0000”表示纯红色。

    • B、 RGB函数,定义为“rgb(red, green, blue)”,变量red、green、blue的取值为[0,255]之间的整数。另外,颜色值也可以为[0%,100%]之间的三个百分比。例如,“rgb(255, 0, 0)”和“rgb(100%, 0%, 0%)”都表示纯红色。

    • C、 HSL(Hue-Saturation-Lightness)函数,定义为“hsl(hue,saturation%, lightness%)”,变量hue为[0,360]一个角度表示颜色(red=0, green=120, blue=240),变量saturation为[0%,100%]之间的一个值(gray=0%,full color=100%),变量lightness为[0%,100%]之间的一个值(black=0%, normal=50%, white=100%)。例如,“hsl(0,100%, 50%)”为纯红色。

    • D、 通用HTML颜色名称,ImageDraw模块提供了140个标准颜色名称,Xwindow系统和大多数web浏览器都支持这些颜色。颜色名称对大小写不敏感。例如,“red”和“Red”都表示纯红色。

    • 在PIL 1.1.4及其以后的版本,用户绘制“RGB”图像时,可以使用字符串常量。PIL支持如下字符串格式:

  • Fonts

    • PIL可以使用bitmap字体或者OpenType/TrueType字体

2、 模块函数

2.1 arc

语法:

draw.arc(xy, start, end, options)

在给定的区域内,在开始和结束角度之间绘制一条弧

options:可以有什么内容可以在源代码中查看

2.2 bitmap

语法:

draw.bitmap(xy, bitmap, options) # options中可以添加 fill 覆盖的颜色

在给定的区域里绘制变量bitmap所对应的位图,非零部分使用变量options中fill的值来填充。变量bitmap位图应该是一个有效的透明模板(模式为“1”)或者蒙版(模式为“L”或者“RGBA”)

变量xy是变量bitmap对应位图起始的坐标值,而不是一个区域

这个方法与Image.paste(xy, color, bitmap)有相同的功能

2.3 chord

语法:

draw.chord(xy, start, end, options)

和方法arc()一样,但是使用直线连接起始点

变量 options 的 outline 给定弦轮廓的颜色;fill 给定弦内部的颜色

2,4 ellipse

语法:

draw.ellipse(xy, options)

在给定的区域绘制一个椭圆形

变量 options 的 outline 给定弦轮廓的颜色;fill 给定弦内部的颜色

2.5 line

语法:

draw.line(xy, options)

在变量xy列表所表示的坐标之间画线

xy里面至少有两个坐标,坐标使用元组表示,存储在一个列表里面[(x1, y1), (x2, y2)]

width指定宽度,fill 指定线的颜色

2.6 pieslice

语法:

draw.pieslice(xy, start, end, options)

和方法arc()一样,但是在指定区域内结束点和中心点之间绘制直线

2.7 point

语法:

draw.point(xy, options)

在指定位置画一个只占一个像素的小点

2.8 polygon

语法:

draw.polygon(xy, options)

绘制一个多边形

多边形轮廓由给定坐标之间的直线组成,在最后一个坐标和第一个坐标间增加了一条直线,形成多边形

坐标列表是包含2元组[(x,y),…]或者数字[x,y,…]的任何序列对象,它最少包括3个坐标值

变量options的fill给定多边形内部的颜色

2.9 rectangle

语法:

draw.rectangle(xy, options)

绘制一个长边形

变量xy是包含2元组[(x,y),…]或者数字[x,y,…]的任何序列对象,它应该包括2个坐标值

注意:当长方形没有没有被填充时,第二个坐标对定义了一个长方形外面的点

变量options的fill给定长边形内部的颜色

2.10 text

语法:

draw.text(xy, string, options)

在给定的位置绘制一个字符串。变量xy给出了文本的左上角的位置

变量option的 font 用于指定所用字体。它应该是类ImangFont的一个实例,使用ImageFont模块的load()方法从文件中加载的

变量options的fill给定文本的颜色

2.11 textsize

语法:

draw.textsize(string, options)

返回给定字符串的大小,以像素为单位

变量option的 font 用于指定所用字体。它应该是类ImangFont的一个实例,使用ImageFont模块的load()方法从文件中加载的

七、 Image与Numpy

from PIL import Image
import numpy as np

im = Image.open("./a.jpg")
print(np.asarray(im)) # 三维数组
na = np.asarray(im) # 将图片转换为数组
na[0][0][0] = 0 # 修改数组的值
im_new = Image.fromarray(na) # 将数组转换为图片
Name Description
ImageFilter.BLUR Fuzzy filtering, that is, mean filtering
ImageFilter.CONTOUR Contour filtering, looking for image contour information
ImageFilter.DETAIL Detail filtering, making the image display more detailed
ImageFilter.FIND_EDGES Looking for boundaries Filtering (finding the boundary information of the image)
ImageFilter.EMBOSS Relief filtering, display the image in the form of a relief image
ImageFilter.EDGE_ENHANCE Border Enhancement Filter
ImageFilter.EDGE_ENHANCE_MORE Depth Edge Enhancement Filter
ImageFilter.SMOOTH Smooth filter
ImageFilter.SMOOTH_MORE Depth smooth filter
ImageFilter.SHARPEN Sharpening filter

The above is the detailed content of How to use the Python image processing library PIL. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete