【发布时间】:2015-10-30 00:55:03
【问题描述】:
我需要使用 numpy 保存一些数组,以便稍后使用 Android Java APP 和另一个使用 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
和
def read_feature_bin_file(filepath):
try:
binf = open(filepath, 'r')
header = numpy.fromfile(f, count=3, dtype=numpy.int32)
print header
rows = header[0]
cols = header[1]
dt = header[2]
if dt == 0:
features = numpy.fromfile(f, dtype=numpy.uint8)
else:
features = numpy.fromfile(f, dtype=numpy.float32)
features.resize(rows, cols)
binf.close()
return features
except Exception as e:
print "Unable to read file: ", filepath
print e
return None
我在这里所做的只是将一个小标题写入输出文件,包含三个整数,描述行数、列数和数据类型,可以是 uint8 或 float32,然后附加其余部分我的数据到文件。读取时,我读取头的前三个元素以检查数组属性,然后相应地读取文件的其余部分。问题是:我不知道这是否安全,尤其是关于要读取此文件的系统的字节序。
对我来说,确保可以在任何系统中正确读取此文件的最佳方法是什么?我知道 numpy 具有“保存”和“加载”功能,它们都以 .npz 或 .npy 格式保存,但我不知道如何将它们移植到我的 Android 应用程序中读取。
【问题讨论】:
-
试试吧。您将很快发现您的 Android 应用程序是否可以正确读取它。什么是 numpy?
-
Pickle 格式应该是可移植的。上面的文档位于docs.python.org/2/library/pickle.html 和docs.python.org/3.1/library/pickle.html。
标签: android python arrays numpy binary