pillow库取代PIL提供Python下轻量级的图像处理工具
pillow库提供的imshow函数是文件形式,比较难用,一般使用matplot库中的matplotlib.pyplot.imshow()函数,该函数提供了对于pillow.Image对象的直接支持。
此外,matplotlib.pyplot.imread库自身也提供了PNG图像加载功能。若已安装pillow库,则其会自动调用以加载其他格式。返回的是标准numpy array。便于计算。
为了在pillow.Image和numpy array之间进行转换,可以使用以下代码:
from PIL import Image
from numpy import array
img = Image.open("input.png")
arr = array(img)
img = Image.fromarray(arr)
或
def array2PIL(arr, size):
mode = 'RGBA'
arr = arr.reshape(arr.shape[0]*arr.shape[1], arr.shape[2])
if len(arr[0]) == 3:
arr = numpy.c_[arr, 255*numpy.ones((len(arr),1), numpy.uint8)]
return Image.frombuffer(mode, size, arr.tostring(), 'raw', mode, 0, 1)