PIL:Python Image Library
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()
![这里写图片描述](https://img-blog.csdn.net/20151210104248494) -
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)