python - Python读取无符号16位整数的二进制文件
问题描述
我必须在 Python 中读取一个二进制文件,并将其内容存储在一个数组中。我在这个文件上的信息是
filename.bin is of size 560x576 (height x width) with 16 b/p, i.e., unsigned 16-bit integer for each pixel
到目前为止,这是我能想到的:
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))
但是我得到了错误
cannot reshape array of size 161280 into shape (560,576)
161280 正好是560 x 576 = 322560
. 我想了解我做错了什么以及如何读取二进制文件并以所需的形式重塑。
解决方案
您使用 'I' 作为 32 位无符号格式,而不是 16 位无符号格式的 'H'。
做这个
a = struct.unpack("H" * ((len(fileContent)) // 2), fileContent)