| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""Read/Write NPZ files. |
| 5 |
|
| 6 |
Backend: `Numpy <https://numpy.org/doc/stable/reference/generated/numpy.savez.html>`_ |
| 7 |
|
| 8 |
NPZ is a file format by numpy that provides storage of array data using gzip |
| 9 |
compression. This imageio plugin supports data of any shape, and also supports |
| 10 |
multiple images per file. However, the npz format does not provide streaming; |
| 11 |
all data is read/written at once. Further, there is no support for meta data. |
| 12 |
|
| 13 |
See the BSDF format for a similar (but more fully featured) format. |
| 14 |
|
| 15 |
Parameters |
| 16 |
---------- |
| 17 |
None |
| 18 |
|
| 19 |
Notes |
| 20 |
----- |
| 21 |
This format is not available on Pypy. |
| 22 |
|
| 23 |
""" |
| 24 |
|
| 25 |
import numpy as np |
| 26 |
|
| 27 |
from ..core import Format |
| 28 |
|
| 29 |
|
| 30 |
class NpzFormat(Format): |
| 31 |
"""See :mod:`imageio.plugins.npz`""" |
| 32 |
|
| 33 |
def _can_read(self, request): |
| 34 |
|
| 35 |
return request.extension in self.extensions |
| 36 |
|
| 37 |
def _can_write(self, request): |
| 38 |
|
| 39 |
return request.extension in self.extensions |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
class Reader(Format.Reader): |
| 44 |
def _open(self): |
| 45 |
|
| 46 |
self._npz = np.load(self.request.get_file()) |
| 47 |
assert isinstance(self._npz, np.lib.npyio.NpzFile) |
| 48 |
|
| 49 |
self._names = sorted(self._npz.files, key=lambda x: x.split("_")[-1]) |
| 50 |
|
| 51 |
def _close(self): |
| 52 |
self._npz.close() |
| 53 |
|
| 54 |
def _get_length(self): |
| 55 |
return len(self._names) |
| 56 |
|
| 57 |
def _get_data(self, index): |
| 58 |
|
| 59 |
if index < 0 or index >= len(self._names): |
| 60 |
raise IndexError("Index out of range while reading from nzp") |
| 61 |
im = self._npz[self._names[index]] |
| 62 |
|
| 63 |
return im, {} |
| 64 |
|
| 65 |
def _get_meta_data(self, index): |
| 66 |
|
| 67 |
raise RuntimeError("The npz format does not support meta data.") |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
class Writer(Format.Writer): |
| 72 |
def _open(self): |
| 73 |
|
| 74 |
|
| 75 |
self._images = [] |
| 76 |
|
| 77 |
def _close(self): |
| 78 |
|
| 79 |
np.savez_compressed(self.request.get_file(), *self._images) |
| 80 |
|
| 81 |
def _append_data(self, im, meta): |
| 82 |
self._images.append(im) |
| 83 |
|
| 84 |
def set_meta_data(self, meta): |
| 85 |
raise RuntimeError("The npz format does not support meta data.") |