1

I must read a binary file in Python, and store its content in an array. The information I have on this file is that

filename.bin is of size 560x576 (height x width) with 16 b/p, i.e., unsigned 16-bit integer for each pixel

This is what I have been able to come up with so far:

import struct
import numpy as np
fileName = "filename.bin"

with open(fileName, mode='rb') as file: 
    fileContent = file.read()



a = struct.unpack("I" * ((len(fileContent)) // 4), fileContent)

a = np.reshape(a, (560,576))

However I get the error

cannot reshape array of size 161280 into shape (560,576)

161280 is exactly half of 560 x 576 = 322560. I would like to understand what I am doing wrong and how to read the binary file and reshape in the required form.

1 Answer 1

3

You are using 'I' for the format which is 32 bit unsigned instead of 'H' which is 16 bit unsigned.

Do this

a = struct.unpack("H" * ((len(fileContent)) // 2), fileContent)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your answer. Just to see if I understood: if instead my file was 560 x 576, 32-bit signed integer per pixel, what I would have to use is `struct.unpack("i" * ((len(fileContent)) // 4), fileContent)' , right?
Yes, but with a capital I for unsigned. Small i is signed.

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.