将1D字节数组转换为2D numpy数组的最快方法 [英] Quickest way to convert 1D byte array to 2D numpy array
本文介绍了将1D字节数组转换为2D numpy数组的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个我可以这样处理的数组:
I've got an array that I can process like this:
ba = bytearray(fh.read())[32:]
size = int(math.sqrt(len(ba)))
我可以判断一个像素应该是黑色还是白色给定
I can tell if a pixel should be black or white given
iswhite = (ba[i]&1)==1
如何快速将我的1D字节数组转换为行长度<$ c的2D numpy数组$ c>尺寸和白色像素为(ba [i]& 1)== 1
,黑色为其他人?我创建这样的数组:
How can I quickly convert my 1D byte array into a 2D numpy array with row length size
and white pixels for (ba[i]&1)==1
and black for others? I create the array like this:
im_m = np.zeros((size,size,3),dtype="uint8)
推荐答案
import numpy as np
# fh containts the file handle
# go to position 32 where the image data starts
fh.seek(32)
# read the binary data into unsigned 8-bit array
ba = np.fromfile(fh, dtype='uint8')
# calculate the side length of the square array and reshape ba accordingly
side = int(np.sqrt(len(ba)))
ba = ba.reshape((side,side))
# toss everything else apart from the last bit of each pixel
ba &= 1
# make a 3-deep array with 255,255,255 or 0,0,0
img = np.dstack([255*ba]*3)
# or
img = ba[:,:,None] * np.array([255,255,255], dtype='uint8')
有几种方法可以完成最后一步。请注意你得到相同的数据类型( uint8
)如果你需要它。
There are several ways to do the last step. Just be careful you get the same data type (uint8
) if you need it.
这篇关于将1D字节数组转换为2D numpy数组的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文