johnhenry
johnhenry

Reputation: 1333

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.

Upvotes: 1

Views: 3150

Answers (1)

Deepstop
Deepstop

Reputation: 3807

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)

Upvotes: 3

Related Questions