Pillow模块的使用

1
2
3
from PIL import Image, ImageColor, ImageFilter,ImageDraw,ImageFont

import os,re

Output Content:

打开图片文件

Image.open(webpfile)

1
2
3
4
5
6
7
8
9
10
11
12
im = Image.open("test.webp")
im

# 文件是否为有效的图片文件

path = r"D:\onedrive\Code\Note\python_module\Pillow\test_1.webp"
try:
with Image.open(path) as im:
print(path, im.format, f"{im.size}@{im.mode}")
except:
pass

Output Content:

图片属性

1
2
3
4
5
6
7
8
9
im.filename     # 'test.webp'
im.size # (487, 640)
im.mode # 'RGB'
im.getbands
im.format # 'JPEG'
im.info
im.readonly
im.width
im.height

Output Content:

'test.webp'

(487, 640)

'RGB'

<bound method Image.getbands of <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=487x640 at 0x7F067F5A3150>>

'JPEG'

{'jfif': 257, 'jfif_version': (1, 1), 'jfif_unit': 0, 'jfif_density': (1, 1)}

0

487

640

图片尺寸

1
2
3
4
5
6
7
8
9
# im.size返回的是一个元组,包含尺寸的width,height
im.size
w,h=im.size
w,h

im.width,im.height

# 图片占用存储空间尺寸,单位bit
os.path.getsize('test.webp')

Output Content:

(487, 640)

(487, 640)

(487, 640)

113104

RGB通道的图片

分离通道

1
2
3
4
5
6
7
8
9
10
11
12
13
# img.split() 返回三元素的元组,各元素就是三个通道的单通道图片
# 分离颜色通道,产生三个 Image对象

webpfile = "test.webp"

img = Image.open(webpfile)
r, g, b = img.split()
r, g, b

print(type(im),type(webpfile))

a,b,c = Image.Image.split(Image.open(webpfile))
a,b,c

Output Content:

(<PIL.Image.Image image mode=L size=487x640>,
 <PIL.Image.Image image mode=L size=487x640>,
 <PIL.Image.Image image mode=L size=487x640>)

<class 'PIL.JpegImagePlugin.JpegImageFile'> <class 'str'>

(<PIL.Image.Image image mode=L size=487x640>,
 <PIL.Image.Image image mode=L size=487x640>,
 <PIL.Image.Image image mode=L size=487x640>)

保存单通道的图片

1
2
3
4
Output Content:
img = Image.open(imgfile)

a,b,c = Image.Image.split(img)

Output Content:

1
2
3
4
5
6
7
8
9
10
11
12
13
# rgb通道分离后, 返回一个元组,分别代表r,g,b  
# 单通道的图片的像素尺寸不变,但是占用的存储空间变小50%以上

imgfile = "test.webp"
img = Image.open(imgfile)
a, b, c = Image.Image.split(img)

a
b
c

a.save("testwebp_chanl_r.webp")

Output Content:

缩放图片尺寸

Image.thumbnail(size, resample=None)

  1. size: 缩略图尺寸,是一个二元元组,形如(width, height)w,h都不应超过源图片尺寸。等比缩放图片。
  2. resample: 样例率算法。可以是下列之一,分别对应不同的样例率算法

resize() 和 thumbnail() 方法的区别

  1. resize()方法可以缩小也可以放大,而thumbnail()方法只能缩小;
  2. resize()方法不会改变原来对象的大小,只会返回一个新的Image对象
  3. thumbnail()方法会直接改变对象的大小,返回值为none;
  4. resize()方法中的size参数直接规定了修改后的大小;
  5. thumbnail()方法按比例缩小,size参数只规定修改后size的最大值。
1
2
3
4
5
6
7
8
9
10
11
12
im =Image.open('test.webp')
w,h = im.size
w,h

im.thumbnail((400,600))
im,im.size

im.thumbnail((200,600),Image.LANCZOS)
im,im.size

im

Output Content:

(487, 640)

(<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=400x526>, (400, 526))

(<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=200x263>, (200, 263))

合并通道

  • Image.merge(mode, bands)
  • 参数说明如下:-
  • mode:指定输出图片的模式
  • bands:参数类型为元组或者列表序列,其元素值是组成图像的颜色通道,比如 RGB 分别代表三种颜色通道,可以表示为 (r,g,b)。
  • 注意,该函数会返回一个新的 Image 对象。

单张图片的通道合成

1
2
3
4
5
6
7
8
9
10
11
12
13
img = Image.open('test.webp')
img
a = img.split()
r, g, b = a

# 返回原图
Image.merge("RGB", a)

# 更改通道顺序 倒序
Image.merge("RGB", a[::-1])

# 更改通道顺序
Image.merge("RGB", (r,b,g))

Output Content:

两张图片的通道合成

要求两张图片的模式、图像大小必须要保持一致,否则不能合并

1
2
3
4
5
6
7
8
9
10
11
img = Image.open("test.webp")
img.thumbnail((400, 800))

img1 = Image.open("test2.webp")
img2 = img1.resize(img.size)
r, g, b = img.split()
x, y, z = img2.split()

Image.merge("RGB", ( r, g,z))

print(img.size, img2.size)

Output Content:

(400, 526) (400, 526)

blend() 混合图片

  • blend() 方法来混合 RGBA 模式的图片(PNG 格式),函数的语法格式如下:
    • Image.blend(image1,image2, alpha)
    • 参数说明如下:
      • image1,image2:表示两个 Image 对象。
      • alpha:表示透明度,取值范围为 0 到 1.
        • 当取值为 0 时,输出图像相当于 image1 的拷贝,
        • 而取值为 1 时,则是 image2 的拷贝,
        • 只有当取值为 0.5 时,才为两个图像的中合。因此改值的大小决定了两个图像的混合程度。
  • 与 RGB 模式相比,RGBA 在 RGB 的基础上增加了透明度,通过 Alpha 取值来决定两个图像的混合程度。
1
2
3
4
5
6
im1 = Image.open("test.webp")
im2 = Image.open("test2.webp")
im3 = im2.resize(im1.size)

Image.blend(im1, im3, 0.3)
Image.blend(im3, im1, 0.3)

Output Content:

composite 混合图片

通过使用透明蒙版混合图像来创建合成图像

Image.composite(im2, im1, im2)

参数

  1. im1 – 第一张图片。。
  2. im2 – 第二张图片。必须是RGBA
1
2
3
4
5
6
7
8
9
10
11
# 打开两张图片
im1 = Image.open("test2.webp")

im2 = Image.open("test.webp")
im2 = im2.convert("RGBA")

im3 = Image.open('test.webp_no_bg.webp')

Image.composite(im2,im1,im2)

Image.composite(im3,im1,im3)

Output Content:

更改图片尺寸

  • 可以放大可以缩小
  • resize()函数讲解
  • 函数img.resize((width, height),Image.ANTIALIAS)
    • 第二个参数:
      Image.NEAREST :低质量
      Image.BILINEAR:双线性
      Image.BICUBIC :三次样条插值
      Image.ANTIALIAS:高质量

按指定的尺寸,不保持纵横比

1
2
out = im.resize((300, 300))
out

Output Content:

1
2
3
4
5
im=Image.open("test.webp")
w, h = im.size

out = im.resize((w //2, h // 2))
out

Output Content:

保持比例

1
2
3
im.thumbnail((200, 800))
im.size
im

Output Content:

(200, 263)

插值

第二个参数:

  • Image.NEAREST :低质量
  • Image.BILINEAR:双线性
  • Image.BICUBIC :三次样条插值
  • Image.LANCZOS:高质量
1
2
3
4
5
6
# 低质量
im=Image.open("test.webp")
im.size
im.thumbnail((300, 800), Image.NEAREST)
im.size
im

Output Content:

(487, 640)

(300, 394)
1
2
3
4
5
# 双线性
im=Image.open("test.webp")
im.thumbnail((300, 800), Image.BILINEAR)
im.size
im

Output Content:

(300, 394)
1
2
3
4
5
# 三次样条插值
im=Image.open("test.webp")
im.thumbnail((300, 800), Image.BICUBIC)
im.size
im

Output Content:

(300, 394)
1
2
3
4
5
# 高质量
im=Image.open("test.webp")
im.thumbnail((300, 800), Image.LANCZOS)
im.size
im

Output Content:

(300, 394)

图像的复制

1
2
3
# 复制图像
a = im.copy()
a

Output Content:

1
2
out = im.rotate(45)
out

Output Content:

expand=True

1
im.rotate(45, expand=True)

Output Content:

图像的镜面翻转

  • Image.FLIP_LEFT_RIGHT 水平翻转
  • Image.FLIP_TOP_BOTTOM,垂直翻转
1
2
3
4
im = Image.open("test.webp")
im.thumbnail((300, 800), Image.LANCZOS)
im.transpose(Image.FLIP_LEFT_RIGHT)
im.transpose(Image.FLIP_TOP_BOTTOM)

Output Content:

获取rgb值及alpha

1
2
3
4
print(ImageColor.getcolor('red', 'RGBA'))

# 也可以只以RBG的方式查看
print(ImageColor.getcolor('black', 'RGB'))

Output Content:

(255, 0, 0, 255)
(0, 0, 0)

新建图像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 通常使用RGB模式就可以了
a = Image.new('RGB', (100, 100), 'red')
a

# 也可以用RGBA模式,还有其他模式查文档吧
b = Image.new('RGB', (200, 100), 'red')
b
# 十六进制颜色
c = Image.new('RGBA', (200, 100), '#FF00b0')
c
# 传入元组形式的RGBA值或者RGB值
# 在RGB模式下,第四个参数失效,默认255,在RGBA模式下,也可只传入前三个值,A值默认255
d = Image.new('RGBA', (200, 100), (255, 255, 0, 200))
d

Output Content:

裁剪图片

1
2
im=Image.open("test.webp")
im.crop((500, 700, 1000, 1000))

Output Content:

图片粘贴

1
2
3
a = im.crop((700, 700, 1000, 1000))
im.paste(a, (0, 0))
im

Output Content:

图像过滤

1
2
3
4
im = Image.open("test.webp")
im.thumbnail((200,1000),Image.LANCZOS)
# 高斯模糊
im.filter(ImageFilter.GaussianBlur)

Output Content:

1
2
# 普通模糊
im.filter(ImageFilter.BLUR)

Output Content:

1
2
# 边缘增强
im.filter(ImageFilter.EDGE_ENHANCE)

Output Content:

1
2
# 找到边缘
im.filter(ImageFilter.FIND_EDGES)

Output Content:

1
2
# 浮雕
im.filter(ImageFilter.EMBOSS)

Output Content:

1
2
# 轮廓
im.filter(ImageFilter.CONTOUR)

Output Content:

1
2
# 锐化
im.filter(ImageFilter.SHARPEN)

Output Content:

1
2
# 平滑
im.filter(ImageFilter.SMOOTH)

Output Content:

1
2
# 细节
im.filter(ImageFilter.DETAIL)

Output Content:

1
2
3
4
5
from PIL import Image, ImageDraw, ImageFont

# 产生一个有4个颜色channels的空白图像
b = Image.new('RGBA', (200, 100), 'BLUE')
b

Output Content:

1
2
3
4
5
6
7
# 在blank_image 图像上绘图
c = ImageDraw.Draw(b)
c

# 画一个矩形
c.rectangle((50,50,100,90),outline='red',fill='blue')
b

Output Content:

<PIL.ImageDraw.ImageDraw at 0x7f067c1bac10>

图像转换

1
2
3
4
5
6
7
8
9
10
# convert()是图像实例对象的一个方法,接受一个 mode 参数,用以指定一种色彩模式
# 1 ------------------(1位像素,黑白,每字节一个像素存储)
# L ------------------(8位像素,黑白)
# P ------------------(8位像素,使用调色板映射到任何其他模式)
# RGB------------------(3x8位像素,真彩色)
# RGBA------------------(4x8位像素,带透明度掩模的真彩色)
# CMYK--------------------(4x8位像素,分色)
# YCbCr--------------------(3x8位像素,彩色视频格式)
# I-----------------------(32位有符号整数像素)
# F------------------------(32位浮点像素)

Output Content:

1
2
3
4
5
6
7
8
# 将彩色转换成灰阶
im = Image.open("test.webp")
im.thumbnail((200, 1000), Image.LANCZOS)
a = im.convert('L')
a
s=im.convert('RGBA')
s.getbands
s

Output Content:

<bound method Image.getbands of <PIL.Image.Image image mode=RGBA size=200x263 at 0x7F067F5C91D0>>
1
2
3
4
5
6
7
8
Image.open('test.webp').convert("RGB").save("test.webp","WEBP")
img3=Image.open("test.webp")
img3.size
img3

import os
os.path.getsize("test.webp")
os.path.getsize("test.webp")

Output Content:

(487, 640)
113104

66374
1
2
3
4
5
6
7
im1=Image.open("test.webp")
im1.size
w,h=im1.size
im2=im1.resize((w*3,h*3))
im2.size
im1
im2.save("test_1.webp")

Output Content:

(487, 640)

(1461, 1920)

更改图像尺寸后另存为webp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

from PIL import Image, ImageColor, ImageFilter
import os,re

path=r'/home/xiaoyx/图片/'
files=[i for i in os.listdir(path) if re.search('\.webp$',i)]

for i in files:
file=os.path.join(path,i)
sz=os.path.getsize(file)/1000

pic=Image.open(file)
print(f'{i}的大小是:{sz} kb,照片的尺寸大小是:{pic.size}')
# pic.thumbnail((800, 800), Image.LANCZOS)
pic=pic.resize((1800, 1800), Image.LANCZOS)
newname=os.path.join(path,i.split('.')[0])
pic.save(f'{newname}.webp','WEBP')
pic.close()

Output Content:

绘制文字

1
2
3
4
5
6
7
icon = Image.new('RGBA', (50, 35),(0,0,0,180) )
icon
draw = ImageDraw.Draw(icon)
font=ImageFont.truetype(font= "malayalam.ttf" ,size=28)
draw.text((0,0),'888',fill=(255,255,255,255),font=font)
icon.save('textpictest.webp')
icon

Output Content:

1
2
3
4
5
6
def creat_icon(text):
icon = Image.new('RGBA', (75, 45),(0,0,0,180) )
draw = ImageDraw.Draw(icon)
font=ImageFont.truetype(font= "malayalam.ttf" ,size=32)
draw.text((0,0),text,fill=(255,255,255,255),font=font)
return icon

Output Content:

1
2
3
4
5
6
7
8
9
10
11
# 创建ICON
icon=creat_icon('Paste')
icon

# 打开图片
im2=Image.open('test.webp')
im2
im2.paste(icon,(0,0),icon)

# 贴上ICON后
im2

Output Content:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 贴图片 
# im1=Image.open('test.webp')
# # im1
# # im1.size

im2 =Image.open('test2.webp')

# im2.paste(im1)
# im2

import numpy as np
im3 = Image.open('test3.webp_no_bg.webp')

size = (np.array(im2.size) - np.array(im3.size))/2
pos = tuple([int(i) for i in tuple(size)])

im2.paste(im3,pos,im3)
im2

im2 =Image.open('test2.webp')
Image.composite(im3,im2,im3)

Output Content:

抠图

removebg模块

– 好像有每天不超过50张的限制

1
2
3
4
5
6
7
8
9
10
11
12
13
# 此模块测试成功
import os
path = '%s/picture'%os.getcwd()
# path

file="test3.webp"
Image.open("test3.webp")
from removebg import RemoveBg
rmbg = RemoveBg("HbFjA4LMQXLTZCnG6TzWuH7R", "error.log") # 引号内是获取的API
rmbg.remove_background_from_img_file(file)

rmbg.remove_background_from_img_file("test.webp")

Output Content:

1
2

Image.open("test3.webp_no_bg.webp")

Output Content: