reading middlebury 'flow' files with python (bytes array & numpy)

a 夏天 提交于 2019-12-03 21:37:51

Try this. I've tested it on one .flo file so far.

import numpy as np
import sys

if __name__ == '__main__':
    if len(sys.argv) <= 1:
        print('Specify a .flo file on the command line.')
    else:
        with open(sys.argv[1], 'rb') as f:
            magic, = np.fromfile(f, np.float32, count=1)
            if 202021.25 != magic:
                print('Magic number incorrect. Invalid .flo file')
            else:
                w, h = np.fromfile(f, np.int32, count=2)
                print(f'Reading {w} x {h} flo file')
                data = np.fromfile(f, np.float32, count=2*w*h)
                # Reshape data into 3D array (columns, rows, bands)
                data2D = np.resize(data, (w, h, 2))
                print(data2D)

bsa's answer does not work for python 3.5 onwards. The small modification shown below, e.g. np.fromfile(f, np.int32, count=1)[0], will.

import numpy as np
import os
import sys

# WARNING: this will work on little-endian architectures (eg Intel x86) only!
if '__main__' == __name__:
    if len(sys.argv) > 1:
        with open(sys.argv[1], 'rb') as f:
            magic = np.fromfile(f, np.float32, count=1)
            if 202021.25 != magic:
                print('Magic number incorrect. Invalid .flo file')
            else:
                w = np.fromfile(f, np.int32, count=1)[0]
                h = np.fromfile(f, np.int32, count=1)[0]
                print('Reading %d x %d flo file' % (w, h))
                data = np.fromfile(f, np.float32, count=2*w*h)
                # Reshape data into 3D array (columns, rows, bands)
                data2D = np.resize(data, (h, w, 2))
    else:
        print('Specify a .flo file on the command line.')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!