来自缓冲区的Numpy 2D-数组? [英] Numpy 2D- Array from Buffer?

查看:77
本文介绍了来自缓冲区的Numpy 2D-数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内存映射,其中包含一个2D数组,我想从中创建一个numpy数组.理想情况下,我希望避免复制,因为涉及的数组可能很大.

I have an memory map, which contains a 2D array and I would like to make a numpy array from it. Ideally, i would like to avoid copying, since the involved array can be big.

我的代码如下:

n_bytes = 10000
tagname = "Some Tag from external System"
map = mmap.mmap(-1, n_bytes, tagname)
offsets = [0, 5000]

columns = []
for offset in offsets:
   #type and count vary in the real code, but for this dummy code I simply made them up. But I know the count and type for every column.
   np_type = np.dtype('f4')
   column_data = np.frombuffer(map, np_type, count=500, offset=offset)
   columns.append(column_data)

# this line seems to copy the data, which I would like to avoid
data = np.array(columns).T

推荐答案

假设您有一个字节数组,并且知道它的尺寸,答案非常简单. 假设您在缓冲区(名为"buff")中原始图像的RGB数据(每像素24位) 尺寸为1024x768

Assuming you have a byte array and you know it's dimensions the answer is very simple. imagine you raw RGB data of an image (24 bit per pixel) in a buffer (named 'buff') dimensions are 1024x768

#read the buffer into 1D byte array
arr = numpy.frombuffer(buff, dtype=numpy.uint8)
#now shape the array as you please
arr.shape = (768,1024,3)

这篇关于来自缓冲区的Numpy 2D-数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆