Python 三: 图像处理
需要 Import 的库
from PIL import Image
import numpy as np
import matplotlib.pyplot as plot
以下所有代码都引用了上述三行代码
基本操作
# 读取图片
img = Image.open("./demo.jpg")
# 获取图片的尺寸
print(img.size)
# > (32, 32)
# 转化为灰度图
grayscale = img.convert('L')
# 转化为二值图
binary = img.convert('1')
# 显示图片
plot.subplot(1, 3, 1)
plot.imshow(img)
plot.subplot(1, 3, 2)
plot.imshow(grayscale)
plot.subplot(1, 3, 3)
plot.imshow(binary)
plot.show()
# np 数组 之间的互相转换
img_array = np.array(img)
img_img = Image.fromarray(img_array)
# 保存图片
binary.save('./binary.png')
新建, 裁剪, 缩放和粘贴
im1 = Image.open("./demo.jpg") # im1 大小为 32 * 32
# 新建一个 64 * 64 的灰度图, 默认填充 0
im2 = Image.new('L', (