PythonWare 公司提供了免费的图像处理工具包 PIL (Python Image Library),该软件包提供了基本的图像处理功能,如:改变图像大小,旋转图像,图像格式转换,色场空间转换,图像增强,直方图处理,插值和滤波等等。
虽然在这个软件包上要实现类似 MATLAB 中的复杂的图像处理算法并不太适合,但是 Python 的快速开发能力以及面向对象等等诸多特点使得它非常适合用来进行原型开发。
1. Image.fromarray ⇔ \Leftrightarrow ⇔ np.asarray
def read_image(path):
img = Image.open(path)
img = img.convert('L')
return np.asarray(img, dtype='float64')/255.
def save_image(array, path):
array[array > 255] = 255
array[array < 0] = 0
array.convert('RGB').save(path)
2. 重要模块及其成员函数
Image.fromarray()
from PIL import Image
import numpy as np
arr = (np.eye(200)*255).astype('uint8')
im = Image.fromarray(arr)
imrgb = Image.merge('RGB', (im, im, im))
imrgb.show()
PIL 读取获得的图像矩阵与 numpy 下的多维数组
import numpy as np
from PIL import Image
img = Image.open(open('./images/3wolfmoon.jpg'))
# Image.open 接受一个文件句柄
img = np.asarray(img, dtype='float64')/255.
img.shape
# (639, 516, 3)
# 做到这一步还不够,如果是彩色图像
# img.shape = (height, width, ndim)
# 并不是 numpy 中所习惯的维度配置
img = img.transpose(2, 0, 1)
img.shape
# (3, 639, 516)