Android 保存二进制文件并读取numpy的最安全方法

Android 保存二进制文件并读取numpy的最安全方法,android,python,arrays,numpy,binary,Android,Python,Arrays,Numpy,Binary,我需要使用numpy保存一些数组,以便稍后使用Android Java应用程序和另一个使用numpy的python应用程序阅读。到目前为止,我一直在为io使用numpy.ndarray.tofile和numpy.ndarray.fromfile,由于两者的简单性,我非常喜欢它们。我写和读这种二进制数组的解决方案是: def write_feature_bin_file(filepath, features_list): if os.path.isfile(filepath): os.r

我需要使用numpy保存一些数组,以便稍后使用Android Java应用程序和另一个使用numpy的python应用程序阅读。到目前为止,我一直在为io使用numpy.ndarray.tofile和numpy.ndarray.fromfile,由于两者的简单性,我非常喜欢它们。我写和读这种二进制数组的解决方案是:

def write_feature_bin_file(filepath, features_list):

if os.path.isfile(filepath):
    os.remove(filepath)

allfeatures = numpy.vstack(features_list)
header = [allfeatures.shape[0]]
try:
    header.append(allfeatures.shape[1])
except Exception as e:
    header.append(1)

if allfeatures.dtype.name == 'uint8':
    header.append(0)
else:
    header.append(5)

header = numpy.array(header, dtype=numpy.int32)

try:
    binf = open(filepath, 'a')
    header.tofile(binf)
    allfeatures.tofile(binf)
    binf.close()
except Exception as e:
    print "Unable to save file: ", filepath
    print e

return

我在这里所做的只是向输出文件写入一个小标题,其中包含三个整数,描述行数、列数和数据类型,可以是uint8或float32,然后将其余数据附加到文件中。读取时,我读取头的前三个元素以检查数组属性,然后相应地读取文件的其余部分。问题是:我不知道这是否安全,特别是关于要读取此文件的系统的结尾

对于我来说,确保在任何系统中都能正确读取此文件的最佳方法是什么?我知道numpy有“保存”和“加载”功能,这两种功能都是以.npz或.npy格式保存的,但我不知道如何将它们移植到我的Android应用程序中阅读。

1。始终以相同的结尾保存

您可以将endianness严格定义为文件格式规范的一部分,并相应地对文件读取器和写入器进行编程。 例如,使用Numpy,可以将endianness指定为:
f4
大端号的一部分。为了始终以little endian格式写入,写入例程可以包含如下内容:

if allfeatures.dtype.name == 'uint8':
    header.append(0)
else:
    allfeatures = allfeatures.astype('<f4', copy=False)
    header.append(5)

header = numpy.array(header, dtype='<i4')

我们试试看。你会很快发现你的Android应用程序是否能正确阅读。什么是numpy?Pickle格式应该是可移植的。上面的文档位于和。谢谢!我特别喜欢在标题的格式化标志上进行编码,这是一个非常聪明的解决方案。
if allfeatures.dtype.name == 'uint8':
    header.append(0)
else:
    allfeatures = allfeatures.astype('<f4', copy=False)
    header.append(5)

header = numpy.array(header, dtype='<i4')
def read_feature_bin_file(filepath):

    with open(filepath, 'rb') as binf:
        header = numpy.fromfile(binf, count=3, dtype='<i4')
        if header[2] not in [1, 5]:  # Check endianness
            header = header.view('>i4')

        rows, cols, dt = header
        dtype = 'u1' if dt==1 else header.dtype.byteorder + 'f4'
        features = numpy.fromfile(binf, dtype)

    features.shape = (rows, cols)
    return features