3

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

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)

1 Answer 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')

There are several ways to do the last step. Just be careful you get the same data type (uint8) if you need it.

Sign up to request clarification or add additional context in comments.

3 Comments

Well I'm having a bit of an issue, here's the full code: pastebin.com/qX69JxpZ I'm trying to export to a jpg, but I get the error "Maximum supported image dimension is 65500 pixels"
The structure seems to be a single outer array with an array within it of pixel arrays (3 number)
@Christian Stewart. I had a typo in my code on the row with reshape. I fixed it. The point is that a.reshape(x,x) returns reshaped version of a (does not reshape it), whereas a.resize((x,x)) or a = a.reshape((x,x)) really change the shape of A. Sorry for the bug!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.