Python Image库简单处理图像

直接列举几个常用的函数,可在 http://effbot.org/imagingbook/image.htm 中查看更多相关函数。

from PIL import Image
import numpy as np

img = Image.open('demo.jpg', 'r') # 打开图片,保存为Image对象
width, height = img.size # 获取图片的大小
new_img = Image.new('RGB', (512, 512), 'red') # 新建Image对象,大小为512×512×3,红色 Image.new('mode', (width, height), 'color')
new_img.putpixel((123, 123), (255, 255, 255)) # 将new_img的(123, 123)处像素颜色改为白色 putpixel((width, height), (r, g, b))
r, g, b = new_img.getpixel((123, 123)) # 获取new_img的(123, 123)处像素的值 getpixel((width, height))
img = img.convert('L') # 将图片转为灰度图片
img.show() # 显示图片
img.save('demo_L.jpg') # 保存图片
data = img.getdata() # 获取图像内容
img_mat = np.matrix(data) # 将Image对象转为矩阵
new_img = Image.fromarray(img_mat) # 将矩阵转为Image对象,需要保证矩阵元素类型为uint8,否则会error
原文地址:https://www.cnblogs.com/menggg/p/11766059.html