| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""Read GDAL files. |
| 5 |
|
| 6 |
Backend: `GDAL <https://gdal.org/>`_ |
| 7 |
|
| 8 |
.. note:: |
| 9 |
To use this plugin you have to install its backend:: |
| 10 |
|
| 11 |
pip install imageio[gdal] |
| 12 |
|
| 13 |
Parameters |
| 14 |
---------- |
| 15 |
none |
| 16 |
""" |
| 17 |
|
| 18 |
from ..core import Format, has_module |
| 19 |
|
| 20 |
_gdal = None |
| 21 |
|
| 22 |
|
| 23 |
def load_lib(): |
| 24 |
global _gdal |
| 25 |
try: |
| 26 |
import osgeo.gdal as _gdal |
| 27 |
except ImportError: |
| 28 |
raise ImportError( |
| 29 |
"The GDAL format relies on the GDAL package." |
| 30 |
"Please refer to http://www.gdal.org/" |
| 31 |
"for further instructions." |
| 32 |
) |
| 33 |
return _gdal |
| 34 |
|
| 35 |
|
| 36 |
GDAL_FORMATS = (".tiff", " .tif", ".img", ".ecw", ".jpg", ".jpeg") |
| 37 |
|
| 38 |
|
| 39 |
class GdalFormat(Format): |
| 40 |
"""See :mod:`imageio.plugins.gdal`""" |
| 41 |
|
| 42 |
def _can_read(self, request): |
| 43 |
if request.extension in (".ecw",): |
| 44 |
return True |
| 45 |
if has_module("osgeo.gdal"): |
| 46 |
return request.extension in self.extensions |
| 47 |
|
| 48 |
def _can_write(self, request): |
| 49 |
return False |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
class Reader(Format.Reader): |
| 54 |
def _open(self): |
| 55 |
if not _gdal: |
| 56 |
load_lib() |
| 57 |
self._ds = _gdal.Open(self.request.get_local_filename()) |
| 58 |
|
| 59 |
def _close(self): |
| 60 |
del self._ds |
| 61 |
|
| 62 |
def _get_length(self): |
| 63 |
return 1 |
| 64 |
|
| 65 |
def _get_data(self, index): |
| 66 |
if index != 0: |
| 67 |
raise IndexError("Gdal file contains only one dataset") |
| 68 |
return self._ds.ReadAsArray(), self._get_meta_data(index) |
| 69 |
|
| 70 |
def _get_meta_data(self, index): |
| 71 |
return self._ds.GetMetadata() |