File: gdal.py

package info (click to toggle)
python-imageio 2.37.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,016 kB
  • sloc: python: 26,044; makefile: 138
file content (71 lines) | stat: -rw-r--r-- 1,653 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# -*- coding: utf-8 -*-
# imageio is distributed under the terms of the (new) BSD License.

""" Read GDAL files.

Backend: `GDAL <https://gdal.org/>`_

.. note::
    To use this plugin you have to install its backend::

        pip install imageio[gdal]

Parameters
----------
none
"""

from ..core import Format, has_module

_gdal = None  # lazily loaded in load_lib()


def load_lib():
    global _gdal
    try:
        import osgeo.gdal as _gdal
    except ImportError:
        raise ImportError(
            "The GDAL format relies on the GDAL package."
            "Please refer to http://www.gdal.org/"
            "for further instructions."
        )
    return _gdal


GDAL_FORMATS = (".tiff", " .tif", ".img", ".ecw", ".jpg", ".jpeg")


class GdalFormat(Format):
    """See :mod:`imageio.plugins.gdal`"""

    def _can_read(self, request):
        if request.extension in (".ecw",):
            return True
        if has_module("osgeo.gdal"):
            return request.extension in self.extensions

    def _can_write(self, request):
        return False

    # --

    class Reader(Format.Reader):
        def _open(self):
            if not _gdal:
                load_lib()
            self._ds = _gdal.Open(self.request.get_local_filename())

        def _close(self):
            del self._ds

        def _get_length(self):
            return 1

        def _get_data(self, index):
            if index != 0:
                raise IndexError("Gdal file contains only one dataset")
            return self._ds.ReadAsArray(), self._get_meta_data(index)

        def _get_meta_data(self, index):
            return self._ds.GetMetadata()