How to use the gdal.UseExceptions function in GDAL

To help you get started, we’ve selected a few GDAL examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github obspy / obspy / obspy / io / shapefile / core.py View on Github external
from osgeo import ogr, osr
    from osgeo.gdal import __version__ as __gdal_version__
except ImportError as e:
    HAS_GDAL = False
    GDAL_VERSION_SUFFICIENT = False
    IMPORTERROR_MSG = str(e) + (
        ". ObsPy's write support for shapefiles requires the 'gdal' module "
        "to be installed in addition to the general ObsPy dependencies.")
    GDAL_TOO_OLD_MSG = str(e) + (
        ". ObsPy's write support for shapefiles requires the 'gdal' module "
        "to be installed in a more recent version.")
else:
    HAS_GDAL = True
    GDAL_VERSION_SUFFICIENT = [1, 7, 3] < list(map(
        to_int_or_zero, __gdal_version__.split(".")))
    gdal.UseExceptions()


def _write_shapefile(obj, filename, **kwargs):
    """
    Write :class:`~obspy.core.inventory.inventory.Inventory` or
    :class:`~obspy.core.event.Catalog` object to a ESRI shapefile.

    :type obj: :class:`~obspy.core.event.Catalog` or
        :class:`~obspy.core.inventory.Inventory`
    :param obj: ObsPy object for shapefile output
    :type filename: str
    :param filename: Filename to write to. According to ESRI shapefile
        definition, multiple files with the following suffixes will be written:
        ".shp", ".shx", ".dbj", ".prj". If filename does not end with ".shp",
        it will be appended. Other files will be created with respective
        suffixes accordingly.
github mcvittal / qpy3 / modules / Raster / RasterProcessing.py View on Github external
def rasterToArray(self, in_raster):
        gdal.UseExceptions()
        gdal.PushErrorHandler('CPLQuietErrorHandler')
        ds = gdal.Open(in_raster).ReadAsArray()
        return ds
github GeoscienceAustralia / COG-Conversion / dea_cogger / cogeo.py View on Github external
#       DEFLATE or LZW can be used for lossless compression, or
#       JPEG for lossy compression
DEFAULT_PROFILE = {'driver': 'GTiff',
                   'interleave': 'pixel',
                   'tiled': True,
                   'blockxsize': 512,  # 256 or 512 pixels
                   'blockysize': 512,  # 256 or 512 pixels
                   'compress': 'DEFLATE',
                   'copy_src_overviews': True,
                   'zlevel': 9}
LOG = structlog.get_logger()

# GDAL Initialisation
os.environ['GDAL_DISABLE_READDIR_ON_OPEN'] = 'YES'
os.environ['CPL_VSIL_CURL_ALLOWED_EXTENSIONS'] = '.tif'
gdal.UseExceptions()


class COGException(Exception):
    pass


class NetCDFCOGConverter:
    """
    Convert the input files to COG style GeoTIFFs
    """

    def __init__(self, black_list=None, white_list=None, no_overviews=None, default_resampling='average',
                 bands_rsp=None, name_template=None, prefix=None, predictor=2):
        # A list of keywords of bands which don't require resampling
        self.no_overviews = no_overviews if no_overviews is not None else []
github commenthol / gdal2tiles-leaflet / gdal2tiles-multiprocess.py View on Github external
def open_input(self):
        """Initialization of the input raster, reprojection if necessary"""

        gdal.UseExceptions()
        gdal.AllRegister()
        if not self.options.verbose:
            gdal.PushErrorHandler('CPLQuietErrorHandler')

        # Initialize necessary GDAL drivers

        self.out_drv = gdal.GetDriverByName(self.tiledriver)
        self.mem_drv = gdal.GetDriverByName('MEM')

        if not self.out_drv:
            raise Exception("The '%s' driver was not found, is it available in this GDAL build?"
                            , self.tiledriver)
        if not self.mem_drv:
            raise Exception("The 'MEM' driver was not found, is it available in this GDAL build?"
                            )
github GitHubRGI / geopackage-python / Tiling / gdal2tiles_parallel.py View on Github external
def open_input(self):
        """Initialization of the input raster, reprojection if necessary"""

        gdal.UseExceptions()
        gdal.AllRegister()
        if not self.options.verbose:
            gdal.PushErrorHandler('CPLQuietErrorHandler')

        # Initialize necessary GDAL drivers

        self.out_drv = gdal.GetDriverByName(self.tiledriver)
        self.mem_drv = gdal.GetDriverByName('MEM')

        if not self.out_drv:
            raise Exception(
                "The '%s' driver was not found, is it available in this GDAL build?",
                self.tiledriver)
        if not self.mem_drv:
            raise Exception(
                "The 'MEM' driver was not found, is it available in this GDAL build?")
github ManishSahu53 / Vector-Map-Generation-from-Aerial-Imagery-using-Deep-Learning-GeoSpatial-UNET / src / postprocess.py View on Github external
def simplify_polygon(path_shp, para, path_output):
    gdal.UseExceptions()
    ogr.UseExceptions()

    def addPolygon(simplePolygon, dst_layer, index):
        featureDefn = dst_layer.GetLayerDefn()
        polygon = ogr.CreateGeometryFromWkb(simplePolygon)
        dst_feat = ogr.Feature(featureDefn)
        dst_feat.SetGeometry(polygon)

        geom = dst_feat.GetGeometryRef()
        dst_feat.SetField('id', index)
        dst_feat.SetField('area', geom.Area())

        dst_layer.CreateFeature(dst_feat)
        dst_layer.SyncToDisk()

    def multipoly2poly(src_lyr, para, dst_layer):
github daleroberts / tv / tv / __init__.py View on Github external
Dale Roberts 

http://www.github.com/daleroberts/tv
"""
import numpy as np
import shutil
import gdal
import sys
import os
import re

from urllib.request import urlopen, URLError
from uuid import uuid4

gdal.UseExceptions()

RESET = bytes('\u001b[0m', 'utf-8')
QUANT = ' ░▒▓█'
CHARS = ' ▄▁▂▃▅▆▇▊▌▎▖▗▘▚▝━┃┏┓┗┛┣┫┳┻╋╸╹╺╻╏──││╴╴╵╵╶╶╵╵⎢⎥⎺⎻⎼⎽▪▙▚▛▜▞▟'
MASKS = [np.array([b == '1' for b in bits]) for bits in
         ['00000000000000000000000000000000',
          '00000000000000001111111111111111',
          '00000000000000000000000000001111',
          '00000000000000000000000011111111',
          '00000000000000000000111111111111',
          '00000000000011111111111111111111',
          '00000000111111111111111111111111',
          '00001111111111111111111111111111',
          '11101110111011101110111011101110',
          '11001100110011001100110011001100',
          '10001000100010001000100010001000',
github cjtu / craterpy / craterpy / dataset.py View on Github external
"""Contains the CraterpyDataset object which wraps gdal.Dataset."""
from __future__ import division, print_function, absolute_import
from craterpy.exceptions import DataImportError
import numpy as np
import gdal
import craterpy.helper as ch
gdal.UseExceptions()  # configure gdal to use Python exceptions


class CraterpyDataset(object):
    """The CraterpyDataset is a specialized version of the GDAL Dataset object.

    The CraterpyDataset only supports simple cylindrically projected datasets.
    It opens files supported by gdal.Open(). If the input file is a GeoTIFF,
    the geographical bounds and resolution will be read automatically.
    Otherwise, all attributes must be passed in the constructor.

    CraterpyDataset inherits all attributes and methods from gdal.Dataset.


    Attributes
    ----------
    nlat, slat, wlon, elon : int or float
github buddebej / dem2tiles / tiler-tools / tiler_backend.py View on Github external
def __init__(self, src=None, dest=None, options=None):

    #----------------------------
        gdal.UseExceptions()

        self.temp_files = []
        self.src = src
        self.dest = dest
        ld('src dest',src, dest)
        self.options = LooseDict(options)
        if self.options.delete_src:
            self.temp_files.append(self.src)
        self.name = self.options.name
        self.tile_ext = self.options.tile_ext
        self.description = ''

        self.init_tile_grid()