简体   繁体   English

将二进制文件读入2D数组python

[英]Reading a binary file into 2D array python

I am having trouble reading a binary file in python and plotting it. 我在读取python中的二进制文件并将其绘制时遇到麻烦。 It is supposedly an unformatted binary file representing a 1000x1000 array of integers. 据推测,它是代表1000x1000整数数组的未格式化二进制文件。 I have used: 我用过:

image = open("file.dat", "r")
a = np.fromfile(image, dtype=np.uint32)

Printing the length returns 500000. I cannot figure out how to create a 2D array out of it. 打印长度返回500000。我不知道如何用它创建2D数组。

Since you are getting half a million uint32 s using 由于您使用了50万个uint32

a = np.fromfile(image, dtype=np.uint32) 

then you will get a million uint16 s using 那么您将获得一百万个uint16

a = np.fromfile(image, dtype=np.uint16) 

There are other possibilities, however. 但是,还有其他可能性。 The dtype could be any 16-bit integer dtype such as dtype可以是任何16位整数dtype,例如

  • >i2 (big-endian 16-bit signed int), or >i2 (big-endian 16位有符号整数),或
  • <i2 (little-endian 16-bit signed int), or <i2 (小尾数16位有符号整数),或
  • <u2 (little-endian 16-bit unsigned int), or <u2 (小尾数16位无符号整数),或
  • >u2 (big-endian 16-bit unsigned int). >u2 (big-endian 16位无符号整数)。

np.uint16 is the same as either <u2 or >u2 depending on the endianness of your machine. np.uint16<u2>u2相同,具体取决于计算机的字节序。


For example, 例如,

import numpy as np
arr = np.random.randint(np.iinfo(np.uint16).max, size=(1000,1000)).astype(np.uint16)
arr.tofile('/tmp/test')
arr2 = np.fromfile('/tmp/test', dtype=np.uint32)
print(arr2.shape)
# (500000,)

arr3 = np.fromfile('/tmp/test', dtype=np.uint16)
print(arr3.shape)
# (1000000,)

Then to get an array of shape (1000, 1000), use reshape: 然后要获得形状数组(1000、1000),请使用reshape:

arr = arr.reshape(1000, 1000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM