Numpy只有整数标量数组可以转换为标量索引 - 升级到3.6

时间:2017-02-27 10:34:27

标签: python arrays numpy

所以我正在阅读.flo,因为我做了一些翘曲。似乎我对Python2.7和numpy版本1.11.2没有任何问题,但是当我升级到Python3.6和numpy版本1.12.0时。

但在转换过程中,我知道第only integer scalar arrays can be converted to a scalar index

会出现错误data2d = np.fromfile(f, np.float32, count=2 * w * h)
import numpy as np


def read_flow(filename):
        f = open(filename, 'rb')
        magic = np.fromfile(f, np.float32, count=1)
        data2d = None

        if 202021.25 != magic:
            print('Magic number incorrect. Invalid .flo file')
        else:
            w = np.fromfile(f, np.int32, count=1)
            h = np.fromfile(f, np.int32, count=1)
            print("Reading %d x %d flo file" % (h, w))
            data2d = np.fromfile(f, np.float32, count=2 * w * h)
            # reshape data into 3D array (columns, rows, channels)
            data2d = np.resize(data2d, (h, w, 2))
        f.close()
        return data2d

可以获取示例.flo文件here

1 个答案:

答案 0 :(得分:3)

如果我使用python 2.7运行你的代码,我会收到以下警告:

  

VisibleDeprecationWarning:使用ndim转换数组> 0到索引将导致将来的返回重塑(newshape,order = order)

出错

原因是np.fromfile()返回一个包含数据而不仅仅是数据的numpy数组 - 即使对于单个元素也是如此。这意味着w = np.fromfile(f,np.int32,count = 1)类似于[512]而不是512。

以下版本适用于python 2.7和3.x

import numpy as np
def read_flow(filename):
        f = open(filename, 'rb')
        magic = np.fromfile(f, np.float32, count=1)
        data2d = None

        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" % (h, w))
            data2d = np.fromfile(f, np.float32, count=2 * w * h)
            # reshape data into 3D array (columns, rows, channels)
            data2d = np.resize(data2d, (h, w, 2))
        f.close()
        return data2d