gdal.py 1.6 KB

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