将1D字节数组快速转换为2D numpy数组的方法

3 投票
1 回答
3512 浏览
提问于 2025-04-18 11:47

我有一个数组,可以这样处理:

ba = bytearray(fh.read())[32:]
size = int(math.sqrt(len(ba)))

我可以根据

iswhite = (ba[i]&1)==1

来判断一个像素是应该是黑色还是白色。

我该如何快速把我的一维字节数组转换成一个二维的numpy数组,行的长度是size,其中白色像素对应(ba[i]&1)==1,其他的则是黑色呢?我这样创建这个数组:

im_m = np.zeros((size,size,3),dtype="uint8)

1 个回答

3
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)。

撰写回答