【问题标题】:How to read binary file data into arrays?如何将二进制文件数据读入数组?
【发布时间】:2017-05-20 19:10:21
【问题描述】:

尝试在 python 中读取二进制文件。来自dataset page

像素存储为无符号字符(1 字节)并从 0 到 255

我尝试了以下方法,它打印 (0,),而不是 784,000 位数组。

# -*- coding: utf8 -*-
# Processed MNIST dataset (http://cis.jhu.edu/~sachin/digit/digit.html)
import struct

f = open('data/data0', mode='rb')
data = []

print struct.unpack('<i', f.read(4))

如何将此二进制文件读入 784,000 位数组(28 字节 x 28 字节 x 1k 样本)或 28x28x1000 3D 数组。我以前从未使用过二进制文件,现在很困惑!

【问题讨论】:

标签: python arrays python-2.7 file binaries


【解决方案1】:

f.read() 将为您提供一个 784,000 字节的不可变数组(在 Python 2 中称为 str)。如果您需要它是可变的,您可以使用array module 及其能够存储各种原语的数组类型,包括无符号字节(由B 代码表示):

from array import array

data = array('B')

with open('data/data0', 'rb') as f:
    data.fromfile(f, 784000)

这可以根据需要切片:

EXAMPLE_SIZE = 24 * 24
examples = [data[s:s + EXAMPLE_SIZE] for s in xrange(0, len(a), EXAMPLE_SIZE)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 2011-12-24
    • 2021-08-30
    • 2021-04-29
    相关资源
    最近更新 更多