Quickest Way To Convert 1d Byte Array To 2d Numpy Array
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]
Solution 1:
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')
There are several ways to do the last step. Just be careful you get the same data type (uint8
) if you need it.
Post a Comment for "Quickest Way To Convert 1d Byte Array To 2d Numpy Array"