您的位置:首页 > 编程语言 > Python开发

Python第三方库使用 —— PIL

2015-12-10 10:43 796 查看
因为语法的简洁,造就了功能的强大,因为开源,全世界的顶尖程序员们(各个行业的)辛勤地无私地也较为容易地为python贡献各式各样的第三方的库,再因为安装的便捷,普及也较为容易。如此种种,造就了python纷繁的世界。

PIL:
Python Image Library


Image.fromarray ⇔ np.asarray

def read_image(path):
img = Image.open(path)
img = img.convert('L')
return np.asarray(img, dtype='float64')/256.

def save_image(array, path):
array[array > 255] = 255
array[array < 0] = 0
array.convert('RGB').save(path)


重要模块及其成员函数

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')/256.
img.shape
# (639, 516, 3)
# 做到这一步还不够,如果是彩色图像
# img.shape = (height, width, ndim)
# 并不是 numpy 中所习惯的维度配置

img = img.transpose(2, 0, 1)
img.shape
# (3, 639, 516)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: