连接 NumPy 与 剩余世界

连接 NumPy 与 剩余世界

# 来源:NumPy Cookbook 2e Ch4

使用缓冲区协议

# 协议在 Python 中相当于接口
# 是一种约束
import numpy as np 
import Image 
# from PIL import Image (Python 3) 
import scipy.misc

lena = scipy.misc.lena() 
# Lena 是 512x512 的灰度图像
# 创建与 Lena 宽高相同的 RGBA 图像,全黑色
data = np.zeros((lena.shape[0], lena.shape[1], 4), dtype=np.int8) 
# 将 data 的不透明度设置为 Lena 的灰度
data[:,:,3] = lena.copy() 

# 将 data 转成 RGBA 的图像格式,并保存
img = Image.frombuffer("RGBA", lena.shape, data, 'raw', "RGBA", 0, 1) 
img.save('lena_frombuffer.png')

# 每个像素都设为 #FC0000FF (红色)
data[:,:,3] = 255 
data[:,:,0] = 222 
img.save('lena_modified.png') 

数组协议

from __future__ import print_function 
import numpy as np 
import Image 
import scipy.misc

# 获取上一节的第一个图像
lena = scipy.misc.lena() 
data = np.zeros((lena.shape[0], lena.shape[1], 4), dtype=np.int8) 
data[:,:,3] = lena.copy() 
img = Image.frombuffer("RGBA", lena.shape, data, 'raw', "RGBA", 0, 1) 

# 获取数组接口(协议),实际上它是个字典
array_interface = img.__array_interface__ 
print("Keys", array_interface.keys())
print("Shape", array_interface['shape']) 
print("Typestr", array_interface['typestr'])
'''
Keys ['shape', 'data', 'typestr'] 
Shape (512, 512, 4) 
Typestr |u1 
'''

# 将图像由 PIL.Image 类型转换回 np.array
numpy_array = np.asarray(img) 
print("Shape", numpy_array.shape) 
print("Data type", numpy_array.dtype)
'''
Shape (512, 512, 4) 
Data type uint8
''' 

与 Matlab 和 Octave 交换数据

# 创建 0 ~ 6 的数组
a = np.arange(7) 
# 将 a 作为 array 保存在 a.mat 中
scipy.io.savemat("a.mat", {"array": a})
'''
octave-3.4.0:2> load a.mat 
octave-3.4.0:3> array 
array =
  0
  1
  ...
  6
'''

# 还可以再读取进来
mat = io.loadmat("a.mat")
print mat
# {'array': array([[0, 1, 2, 3, 4, 5, 6]]), '__version__': '1.0', '__header__': 'MATLAB 5.0 MAT-file Platform: nt, Created on: Sun Jun 11 18:48:29 2017', '__globals__': []}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 来源:NumPy Tutorial - TutorialsPoint 译者:飞龙 协议:CC BY-NC-SA 4...
    布客飞龙阅读 32,980评论 6 98
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,908评论 18 139
  • 先决条件 在阅读这个教程之前,你多少需要知道点python。如果你想从新回忆下,请看看Python Tutoria...
    舒map阅读 2,601评论 1 13
  • NumPy是Python中关于科学计算的一个类库,在这里简单介绍一下。 来源:https://docs.scipy...
    灰太狼_black阅读 1,251评论 0 5
  • 据报道,吕梁的一个女硕士在参加当地事业单位招聘的时候,通过了笔试,应该是面试了,可就因为她的专业是“世界史”,而人...
    烦人的昵称阅读 179评论 0 0