numpy - Reading a binary file into 2D array python -
i having trouble reading binary file in python , plotting it. supposedly unformatted binary file representing 1000x1000 array of integers. have used:
image = open("file.dat", "r") = np.fromfile(image, dtype=np.uint32) printing length returns 500000. cannot figure out how create 2d array out of it.
since getting half million uint32s using
a = np.fromfile(image, dtype=np.uint32) then million uint16s using
a = np.fromfile(image, dtype=np.uint16) there other possibilities, however. dtype 16-bit integer dtype such
>i2(big-endian 16-bit signed int), or<i2(little-endian 16-bit signed int), or<u2(little-endian 16-bit unsigned int), or>u2(big-endian 16-bit unsigned int).
np.uint16 same either <u2 or >u2 depending on endianness of machine.
for example,
import numpy 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 array of shape (1000, 1000), use reshape:
arr = arr.reshape(1000, 1000)
Comments
Post a Comment