我编写了以下代码,以防有人需要解析整个图像数据集(如问题标题中所示),而不仅仅是前两个字节。
import numpy as np
import struct
with open('samples/t10k-images-idx3-ubyte','rb') as f:
magic, size = struct.unpack(">II", f.read(8))
nrows, ncols = struct.unpack(">II", f.read(8))
data = np.fromfile(f, dtype=np.dtype(np.uint8).newbyteorder('>'))
data = data.reshape((size, nrows, ncols))
这假设您解压缩了.gz
文件。您还可以使用压缩文件,如下所示马克托迪斯科的回答 https://stackoverflow.com/a/68875266/3671939, 通过增加import gzip
, using gzip.open(...)
代替open(...)
,并使用np.frombuffer(f.read(), ...)
代替np.fromfile(f, ...)
.
只是为了检查,显示第一个数字。就我而言,它是 7。
import matplotlib.pyplot as plt
plt.imshow(data[0,:,:], cmap='gray')
plt.show()
另外,下面的代码读取带标签的文件
with open('samples/t10k-labels-idx1-ubyte','rb') as f:
magic, size = struct.unpack(">II", f.read(8))
data = np.fromfile(f, dtype=np.dtype(np.uint8).newbyteorder('>'))
data = data.reshape((size,)) # (Optional)
print(data)
# Prints: [7 2 1 ... 4 5 6]
最后一次重塑可以是(size,)
or (1, size)
取决于你的标准。