Python Imaging Library,Python的图像处理核心库
灰度图片是单通道组成
彩色图片是三通道RGB组成
真彩色图片是四通道RGBA组成
RGB
RGBA
…
左上角为原点(0, 0)
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()
from PIL import Image
img = Image.open('../20240110/img/1.jpg')
img = img.resize((50, 100), box=(0, 0, 100, 100))
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()
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')
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()
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()
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()
"""
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()