我有一个Numpy数组类型的矩阵。我怎么把它作为映像写到磁盘上呢?任何格式都可以(png, jpeg, bmp…)一个重要的限制是PIL不存在。
当前回答
纯Python(2 & 3),一个没有第三方依赖的代码片段。
这个函数写入压缩的真彩色(每像素4字节)RGBA PNG。
def write_png(buf, width, height):
""" buf: must be bytes or a bytearray in Python3.x,
a regular string in Python2.x.
"""
import zlib, struct
# reverse the vertical line order and add null bytes at the start
width_byte_4 = width * 4
raw_data = b''.join(
b'\x00' + buf[span:span + width_byte_4]
for span in range((height - 1) * width_byte_4, -1, - width_byte_4)
)
def png_pack(png_tag, data):
chunk_head = png_tag + data
return (struct.pack("!I", len(data)) +
chunk_head +
struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head)))
return b''.join([
b'\x89PNG\r\n\x1a\n',
png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
png_pack(b'IDAT', zlib.compress(raw_data, 9)),
png_pack(b'IEND', b'')])
... 数据应该直接写入以二进制文件打开的文件中,如:
data = write_png(buf, 64, 64)
with open("my_image.png", 'wb') as fh:
fh.write(data)
原始来源 参见:Rust Port来自这个问题。 感谢@Evgeni Sergeev的示例用法:https://stackoverflow.com/a/21034111/432509
其他回答
@ideasman42回答的附录:
def saveAsPNG(array, filename):
import struct
if any([len(row) != len(array[0]) for row in array]):
raise ValueError, "Array should have elements of equal size"
#First row becomes top row of image.
flat = []; map(flat.extend, reversed(array))
#Big-endian, unsigned 32-byte integer.
buf = b''.join([struct.pack('>I', ((0xffFFff & i32)<<8)|(i32>>24) )
for i32 in flat]) #Rotate from ARGB to RGBA.
data = write_png(buf, len(array[0]), len(array))
f = open(filename, 'wb')
f.write(data)
f.close()
所以你可以这样做:
saveAsPNG([[0xffFF0000, 0xffFFFF00],
[0xff00aa77, 0xff333333]], 'test_grid.png')
生产test_grid.png:
(透明性也可以通过减少0xff的高字节来工作。)
这个世界可能不需要另一个包来将numpy数组写入PNG文件,但对于那些无法满足的人,我最近在github上发布了numpngw:
https://github.com/WarrenWeckesser/numpngw
在pypi上:https://pypi.python.org/pypi/numpngw/
唯一的外部依赖项是numpy。
下面是存储库的examples目录中的第一个示例。基本路线很简单
write_png('example1.png', img)
其中img是一个numpy数组。该行之前的所有代码都是导入语句和创建img的代码。
import numpy as np
from numpngw import write_png
# Example 1
#
# Create an 8-bit RGB image.
img = np.zeros((80, 128, 3), dtype=np.uint8)
grad = np.linspace(0, 255, img.shape[1])
img[:16, :, :] = 127
img[16:32, :, 0] = grad
img[32:48, :, 1] = grad[::-1]
img[48:64, :, 2] = grad
img[64:, :, :] = 127
write_png('example1.png', img)
下面是它创建的PNG文件:
另外,我使用了numpngw。write_apng在Voronoi图表中创建动画。
一个答案使用PIL(只是在情况下它是有用的)。
给定一个numpy数组" a ":
from PIL import Image
im = Image.fromarray(A)
im.save("your_file.jpeg")
你可以用几乎任何你想要的格式替换“jpeg”。更多关于格式的细节请点击这里
您可以使用PyPNG。它是一个纯Python(无依赖)开源PNG编码器/解码器,它支持将NumPy数组写入图像。
你可以在Python中使用'skimage'库
例子:
from skimage.io import imsave
imsave('Path_to_your_folder/File_name.jpg',your_array)
推荐文章
- 如何读取文件的前N行?
- 如何删除matplotlib中的顶部和右侧轴?
- 解析.py文件,读取AST,修改它,然后写回修改后的源代码
- Visual Studio Code:如何调试Python脚本的参数
- 使用元组/列表等等。从输入vs直接引用类型如list/tuple/etc
- 结合conda环境。Yml和PIP requirements.txt
- 将命名元组转换为字典
- 如何使x轴和y轴的刻度相等呢?
- Numpy在这里函数多个条件
- 在Python中,使用argparse只允许正整数
- 如何排序mongodb与pymongo
- 不可变与可变类型
- 列表是线程安全的吗?
- 点击下载Href图片链接
- 操作系统。makdirs在我的路径上不理解“~”