PIL
Python Imaging Library,Python的图像处理核心库
通道bands
灰度图片是单通道组成
彩色图片是三通道RGB组成
真彩色图片是四通道RGBA组成
模式
RGB
RGBA
…
坐标系统
左上角为原点(0, 0)
图像操作
显示图像
- show
创建图像
- open()打开图像
- new()创建Image对象
- numpy数组创建Image对象
打开图像
import numpy as np
from PIL import Image
img = Image.open('../20240110/img/1.jpg')
# print(img.mode)
# RGB
# print(img.size)
# (640, 480)
img_data = np.array(img)
print(img_data.shape)
# (480, 640, 3)
# img.show()
创建图像
from PIL import Image
import numpy as np
arr = np.zeros((300, 400, 3), dtype=np.uint8)
print(arr.shape)
# (300, 400, 3)
h, w, c = arr.shape
arr[:, :w//2] = (0, 0, 255)
arr[:, w//2:] = (255, 255, 0)
# np数组转换为PIL图像
img = Image.fromarray(arr)
img.show()
保存图像
from PIL import Image
img = Image.open('../20240110/img/1.jpg')
# img.convert(mode='RGB')
# img.save('../20240110/img/1_bak.png')
img = img.resize((100, 100))
img.show()
Image属性
- mode
- size
- weight
- height
- format
图片格式转换
- save()保存图像
- convert()图像格式转换
图像缩放
- resize()实现任意缩小和放大图像
- size
- resample
- box
from PIL import Image
img = Image.open('../20240110/img/1.jpg')
img = img.resize((50, 100), box=(0, 0, 100, 100))
img.show()
图像分离与合并
- split
- merge
分割图像
from PIL import Image
img = Image.open('snower.jpg')
# RGB
r, g, b = img.split()
r.show()
g.show()
b.show()
img.show()
# img = Image.merge(mode='RGB', bands=(r, g, b))
# img.show()
合并图像
from PIL import Image
img = Image.open('snower.jpg')
# RGB
r, g, b = img.split()
# r.show()
# g.show()
# b.show()
# img.show()
img = Image.merge(mode='RGB', bands=(r, g, b))
img.show()
图像裁剪
- crop
from PIL import Image
img = Image.open('snower.jpg')
w, h = img.size
box_left = (0, 0, w // 2, h)
crop_img_left = img.crop(box_left)
crop_img_left.show()
box_right = (w // 2, 0, w, h)
crop_img_right = img.crop(box_right)
crop_img_right.show()
图像几何变换
- transpose
- rotate
旋转
from PIL import Image
img = Image.open('snower.jpg')
# 旋转
img = img.transpose(Image.Transpose.ROTATE_90)
img.show()
# 旋转 平移
# img = img.rotate(45, translate=(50, 50), fillcolor='blue')
# img.show()
旋转+填充颜色
from PIL import Image
img = Image.open('snower.jpg')
# 旋转
# img = img.transpose(Image.Transpose.ROTATE_90)
# img.show()
# 旋转 平移
img = img.rotate(45, translate=(50, 50), fillcolor='blue')
img.show()
图像粘贴
- paste
from PIL import Image
img_snow = Image.open('snower.jpg')
img_py = Image.open('py.jpg')
w, h = img_py.size
# 176 100
img_snow.paste(img_py, box=(0, 50, w, 50 + h))
img_snow.show()
图像上添加文字
- ImageDraw
- ImageFont
- text
- np创建PIL图像
- fromarray
"""
1. 图像 画布
2. 使用工具
3. 绘制
"""
from PIL import Image, ImageDraw, ImageFont
img = Image.open('snower.jpg')
draw = ImageDraw.Draw(img)
# font = ImageFont.truetype('', size=24)
draw.text((100, 50), text='hello world', fill='blue')
img.show()