Python读取无符号16位整数的二进制文件

Python读取无符号16位整数的二进制文件,python,binary,format,Python,Binary,Format,我必须读取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, mod

我必须读取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正好是560x576=322560的一半。我想了解我做错了什么,以及如何读取二进制文件并以所需的形式重新格式化。

您使用的是32位无符号格式的“I”,而不是16位无符号格式的“H”

这样做

a = struct.unpack("H" * ((len(fileContent)) // 2), fileContent)

谢谢你的回答。看看我是否理解:如果我的文件是560x576,每像素32位有符号整数,那么我必须使用“struct.unpack”(“I”*((len(fileContent))//4),fileContent)”,对吗?是的,但大写I表示无符号。我签名了。