Q:

Python read binary file of unsigned 16 bit integers

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.

A:

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)

