1

Could you please help to unpack the binary file in Python 3? It is an image 2580*7839 size, 4-byte float. What I had in the code for Python 2 and it worked, but not in Python 3.

bformat= ">%sf"
ns = 2580*7839*4
#open file f
byte_arr=f.read(ns)
unpacked_bytes = unpack(bformat % (ns/4), byte_arr)
data=np.array(unpacked_bytes).reshape(7839,2580)
print ('min value', data.min())
print ('max value', data.max())

I get the error message "struct.error: bad char in struct format"

Thanks!

3
  • Why don't you use a library like PIL for this? Commented Mar 10, 2015 at 14:41
  • because I need only the pixel values and then I work with arrays Commented Mar 10, 2015 at 15:45
  • But using pixels = img.load() would be sufficient for every format when using PIL. Nevertheless it seems like the unpacking format doesn't match the old format, you might want to investigate in this, or just take the advantage of using a fully powered imaging library. Commented Mar 10, 2015 at 19:51

1 Answer 1

1

What about using struct?

import struct

f0 = struct.unpack('>f', f.read(4))[0]
f1 = struct.unpack('>f', f.read(4))[0]
f2 = struct.unpack('>f', f.read(4))[0]
....

of better in the loop

for i in range(0, 2580*7839):
    ff = struct.unpack('>f', f.read(4))[0]
    print(i,ff)

it will break somewhere and you'll know where

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

2 Comments

I do use struct. I think it is only about wrong bformat= ">%sf", but I don't know how to correct it
ok, what about trying what I proposed? You think you have array of big-endian float, so in the loop for i in range(0,2580*7839): ff=struct.unpack('>f', f.read(4))[0] and then print i and ff. You'll know where it breaks

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.