Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading binary data as BGRA image with NumPy

I have a BGRA image dumped to a binary file in the following format (serially): [(b, g, r, a), (b, g, r, a), (b, g, r, a) ...] I know the image width, height & # of channels (4 of course in this case).

I want to read the image into a 4D array where the first dimension represents the B values, etc. I have the following code:

data = np.fromfile(fbin, np.dtype('B'))
print data

This prints something like:

[ 79  90  92   0  80  91  93   0  84  96  98   0 ...]

Where 79 is B, 90 is G, 92 is R and 0 is A, and so on. Now I tried to reshape 'data' like this:

print data.reshape(channels, height, width)

Got the following:

[[[ 79  90  92   0  ...] .. [] ..]

  [[109 ...] .. [] ..]

  [[118 ...] .. [] ..]

  [[  0 ...] .. [] ..]]

Where as what I would like to get is something like this:

[[[ 79 ...] .. [] ..]

  [[90 ...] .. [] ..]

  [[92...] .. [] ..]

  [[0...] .. [] ..]]
like image 574
poli_g Avatar asked Apr 10 '26 15:04

poli_g


1 Answers

Well, this feels almost too easy, the solution is:

data = data.reshape(channels, width, height, order='F')
like image 73
poli_g Avatar answered Apr 13 '26 05:04

poli_g