如何将图像目录转换为 .gz?

How do I convert a directory of images into a .gz?

我正在使用 Python,我有几个图像目录,我想将其转换为 .gz 文件,这样我就可以按照烤宽面条教程进行操作。本教程使用存储在单个 .gz 文件中的训练图像。我也在尝试将我的图像目录转换为 .gz,以便我可以模拟教程代码并更好地理解它。

特别是,我试图了解 MNIST .gz 文件的格式,例如 train-images-idx3-ubyte.gzDr. LeCun's website.

中找到的格式

我可以将单个图像转换为 .gz,但不能转换为目录。我的在线搜索表明这应该是预料之中的。我将如何创建包含多个训练图像信息的 .gz 文件?

如果您需要更多信息,或者我问错了问题或方向不明智,请告诉我。谢谢

你不能。 gzip 是一种流压缩方法,它不是容器。在这种情况下,图像存储在文件容器中,在页面底部有描述:

the IDX file format is a simple format for vectors and multidimensional matrices of various numerical types. The basic format is magic number size in dimension 0 size in dimension 1 size in dimension 2 ..... size in dimension N data

The magic number is an integer (MSB first). The first 2 bytes are always 0.

The third byte codes the type of the data: 0x08: unsigned byte 0x09: signed byte 0x0B: short (2 bytes) 0x0C: int (4 bytes) 0x0D: float (4 bytes) 0x0E: double (8 bytes)

The 4-th byte codes the number of dimensions of the vector/matrix: 1 for vectors, 2 for matrices....

The sizes in each dimension are 4-byte integers (MSB first, high endian, like in most non-Intel processors).

The data is stored like in a C array, i.e. the index in the last dimension changes the fastest.

一种更典型的方法是使用压缩包存档作为容器,然后压缩存档。好处是这是创建 gzip 压缩档案的标准方法,不需要自定义脚本来提取文件。

关于如何使用给定的图像目录执行此操作的示例如下(在 *Nix 系统上使用 Bash):

tar -zcvf tar-archive-name.tar.gz source-folder-name

Gzip 压缩是内置的 -z 标志,或者您也可以使用 gzip 命令来执行您自己的操作。

在 Python 中,您还可以创建一个 tarfile 存档,使用 gzip 压缩:

一个简单的例子,修改自documentation,如下:

import tarfile
tar = tarfile.open("sample.tar", "w:gz")
for name in ["foo", "bar", "quux"]:
    tar.add(name)
tar.close()

模式'w:gz'指定存档将被gzip压缩,这适用于任何操作系统。