How to use GDAL - 10 common examples

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 sourcepole / ogrtools / ogrtools / pyogr / ogr2ogr.py View on Github external
pfnProgress, pProgressArg):
                print(
                    "Terminating translation prematurely after failed\n" +
                    "translation from sql statement.")

                return False

            poDS.ReleaseResultSet(poResultSet)


#/* -------------------------------------------------------------------- */
#/*      Special case for layer interleaving mode.                       */
#/* -------------------------------------------------------------------- */
    elif bSrcIsOSM and gdal.GetConfigOption("OGR_INTERLEAVED_READING", None) is None:

        gdal.SetConfigOption("OGR_INTERLEAVED_READING", "YES")

        # if (bSplitListFields)
        #{
        #    fprintf( stderr, "FAILURE: -splitlistfields not supported in this mode\n" );
        #    exit( 1 );
        #}

        nSrcLayerCount = poDS.GetLayerCount()
        pasAssocLayers = [AssociatedLayers() for i in range(nSrcLayerCount)]

#/* -------------------------------------------------------------------- */
#/*      Special case to improve user experience when translating into   */
#/*      single file shapefile and source has only one layer, and that   */
#/*      the layer name isn't specified                                  */
#/* -------------------------------------------------------------------- */
github qgiscloud / qgis-cloud-plugin / qgiscloud / pyogr / ogr2ogr.py View on Github external
#/*      Get other info.                                                 */
#/* -------------------------------------------------------------------- */
    poSrcFDefn = poSrcLayer.GetLayerDefn()

    if poOutputSRS is None:
        poOutputSRS = poSrcLayer.GetSpatialRef()

#/* -------------------------------------------------------------------- */
#/*      Find the layer.                                                 */
#/* -------------------------------------------------------------------- */

    #/* GetLayerByName() can instanciate layers that would have been */
    #*/ 'hidden' otherwise, for example, non-spatial tables in a */
    #*/ Postgis-enabled database, so this apparently useless command is */
    #/* not useless... (#4012) */
    gdal.PushErrorHandler('CPLQuietErrorHandler')
    poDstLayer = poDstDS.GetLayerByName(pszNewLayerName)
    gdal.PopErrorHandler()
    gdal.ErrorReset()

    iLayer = -1
    if poDstLayer is not None:
        nLayerCount = poDstDS.GetLayerCount()
        for iLayer in range(nLayerCount):
            poLayer = poDstDS.GetLayer(iLayer)
            # The .cpp version compares on pointers directly, but we cannot
            # do this with swig object, so just compare the names.
            if poLayer is not None \
                and poLayer.GetName() == poDstLayer.GetName():
                break

        if (iLayer == nLayerCount):
github sourcepole / ogrtools / ogrtools / ogrtransform / ogrconfig.py View on Github external
def find_ogr_layer(ds, layerName):
    # From ogr2ogr.py:
    #/* GetLayerByName() can instanciate layers that would have been */
    #*/ 'hidden' otherwise, for example, non-spatial tables in a */
    #*/ Postgis-enabled database, so this apparently useless command is */
    # /* not useless... (#4012) */
    gdal.PushErrorHandler('CPLQuietErrorHandler')
    poDstLayer = ds.GetLayerByName(layerName)
    gdal.PopErrorHandler()
    gdal.ErrorReset()

    iLayer = None
    if poDstLayer is not None:
        nLayerCount = ds.GetLayerCount()
        for iLayer in range(nLayerCount):
            poLayer = ds.GetLayer(iLayer)
            # The .cpp version compares on pointers directly, but we cannot
            # do this with swig object, so just compare the names.
            if poLayer is not None and poLayer.GetName() == poDstLayer.GetName():
                    break

        if (iLayer == nLayerCount):
            # /* shouldn't happen with an ideal driver */
github OSGeo / gdal / autotest / gcore / tiff_write.py View on Github external
for quality in [90, 75, 30]:
        src_ds = gdal.Open('../gdrivers/data/utm.tif')

        ds = gdal.GetDriverByName('GTiff').Create('tmp/tiff_write_91.tif', 1024, 1024, 3, \
            options = [ 'COMPRESS=JPEG', 'PHOTOMETRIC=YCBCR', 'JPEG_QUALITY=%d' % quality ])

        data = src_ds.GetRasterBand(1).ReadRaster(0, 0, 512, 512, 1024, 1024)
        ds.GetRasterBand(1).WriteRaster(0, 0, 1024, 1024, data)
        ds.GetRasterBand(2).WriteRaster(0, 0, 1024, 1024, data)
        ds.GetRasterBand(3).WriteRaster(0, 0, 1024, 1024, data)
        ds = None

        ds = gdal.Open('tmp/tiff_write_91.tif', gdal.GA_Update)
        gdal.SetConfigOption('JPEG_QUALITY_OVERVIEW', '%d' % quality)
        ds.BuildOverviews( 'NEAR', overviewlist = [2, 4])
        gdal.SetConfigOption('JPEG_QUALITY_OVERVIEW', None)

        src_ds = None
        ds = None

        f = open('tmp/tiff_write_91.tif', 'rb')
        f.seek(0, os.SEEK_END)
        size = f.tell()
        f.close()

        print('quality = %d, size = %d' % (quality, size))

        if quality != 90:
            if size >= last_size:
                gdaltest.post_reason('did not get decreasing file sizes')
                print(size)
                print(last_size)
github OSGeo / gdal / autotest / gcore / tiff_write.py View on Github external
last_size = 0
    for quality in [90, 75, 30]:

        try:
            os.remove('tmp/tiff_write_93.tif.ovr')
        except:
            pass
        
        ds = gdal.Open('tmp/tiff_write_93.tif')
        gdal.SetConfigOption('COMPRESS_OVERVIEW', 'JPEG')
        gdal.SetConfigOption('JPEG_QUALITY_OVERVIEW', '%d' % quality)
        gdal.SetConfigOption('PHOTOMETRIC_OVERVIEW', 'YCBCR')
        ds.BuildOverviews( 'NEAR', overviewlist = [2, 4])
        gdal.SetConfigOption('COMPRESS_OVERVIEW', None)
        gdal.SetConfigOption('JPEG_QUALITY_OVERVIEW', None)
        gdal.SetConfigOption('PHOTOMETRIC_OVERVIEW', None)
        ds = None

        f = open('tmp/tiff_write_93.tif.ovr', 'rb')
        f.seek(0, os.SEEK_END)
        size = f.tell()
        f.close()

        print('quality = %d, size = %d' % (quality, size))

        if quality != 90:
            if size >= last_size:
                gdaltest.post_reason('did not get decreasing file sizes')
                print(size)
                print(last_size)
                return 'fail'
github OSGeo / gdal / autotest / gcore / tiff_write.py View on Github external
md = new_ds.GetMetadataItem( 'AREA_OR_POINT' )
    new_ds = None
    src_ds = None
    
    gt_expected = (440690.0, 60.0, 0.0, 3751350.0, 0.0, -60.0)

    if gt != gt_expected:
        print(gt)
        gdaltest.post_reason( 'did not get expected geotransform when ignoring PixelIsPoint' )
        return 'fail'

    if md != 'Point':
        gdaltest.post_reason( 'did not get expected AREA_OR_POINT value' )
        return 'fail'

    gdal.SetConfigOption( 'GTIFF_POINT_GEO_IGNORE', 'FALSE' )

    # read back this file with pixelispoint behavior enabled.
    
    new_ds = gdal.Open( 'tmp/test_97_2.tif' )
    
    gt = new_ds.GetGeoTransform()
    md = new_ds.GetMetadataItem( 'AREA_OR_POINT' )
    new_ds = None
    
    gt_expected = (440660.0, 60.0, 0.0, 3751380.0, 0.0, -60.0)

    if gt != gt_expected:
        print(gt)
        gdaltest.post_reason( 'did not get expected geotransform when ignoring PixelIsPoint (2)' )
        return 'fail'
github OSGeo / gdal / autotest / gcore / tiff_write.py View on Github external
len = f.tell()
    f.seek(0, 0)
    data = f.read(len-1)
    f.close()
    f = open('tmp/tiff_write_88_src.tif', 'wb')
    f.write(data)
    f.close()
    
    src_ds = gdal.Open('tmp/tiff_write_88_src.tif')
    # for testing only. We need to keep the file to check it was a bigtiff
    gdal.SetConfigOption('GTIFF_DELETE_ON_ERROR', 'NO') 
    gdal.PushErrorHandler('CPLQuietErrorHandler')
    ds = gdaltest.tiff_drv.CreateCopy('tmp/tiff_write_88_dst.tif', src_ds,
            options = ['TILED=YES', 'COPY_SRC_OVERVIEWS=YES', 'ENDIANNESS=LITTLE'])
    gdal.PopErrorHandler()
    gdal.SetConfigOption('GTIFF_DELETE_ON_ERROR', None)
    ds = None
    src_ds = None
    
    f = open('tmp/tiff_write_88_dst.tif', 'rb')
    data = f.read(8)
    f.close()

    os.remove( 'tmp/tiff_write_88_src.tif' )
    os.remove( 'tmp/tiff_write_88_dst.tif' )

    import struct
    ar = struct.unpack('B' * 8, data)
    if ar[2] != 43:
        gdaltest.post_reason('not a BIGTIFF file')
        print(ar)
        return 'fail'
github OpenDrift / opendrift / tests / integration / test_run.py View on Github external
gdal.CE_Fatal:'Fatal'
    }
    err_msg = err_msg.replace('\n',' ')
    err_class = errtype.get(err_class, 'None')
    print('Error Number: %s' % (err_num))
    print('Error Type: %s' % (err_class))
    print('Error Message: %s' % (err_msg))

try:
    import ogr
    import osr
    import gdal
    version_num = int(gdal.VersionInfo('VERSION_NUM'))
    if version_num >= 2000000:
        has_ogr = True
        gdal.PushErrorHandler(gdal_error_handler)
    else:
        print('GDAL version >= 2.0 is required:')
        has_ogr = False
except Exception as e:
    print('GDAL is not available:')
    print(e)
    has_ogr = False

class TestRun(unittest.TestCase):
    """Tests for (non-scalar) LagrangianArray"""

    def make_OceanDrift_object(self):
        self.o = OceanDrift(loglevel=30)
        self.fake_eddy = reader_ArtificialOceanEddy.Reader(2, 62)
        self.o.use_block = False
        self.reader_landmask = reader_global_landmask.Reader(
github OSGeo / gdal / autotest / gcore / tiff_write.py View on Github external
def tiff_write_63():

    md = gdaltest.tiff_drv.GetMetadata()
    if md['DMD_CREATIONOPTIONLIST'].find('BigTIFF') == -1:
        return 'skip'
    try:
        if int(gdal.VersionInfo('VERSION_NUM')) < 1700:
            return 'skip'
    except:
    # OG-python bindings don't have gdal.VersionInfo. Too bad, but let's hope that GDAL's version isn't too old !
        pass 

    gdal.PushErrorHandler('CPLQuietErrorHandler')
    ds = gdaltest.tiff_drv.Create( 'tmp/bigtiff.tif', 150000, 150000, 1,
                                   options = ['BIGTIFF=NO'] )
    gdal.PopErrorHandler()

    if ds is None:
        return 'success'

    return 'fail'
github OpenDrift / opendrift / tests / test_run.py View on Github external
gdal.CE_Fatal:'Fatal'
    }
    err_msg = err_msg.replace('\n',' ')
    err_class = errtype.get(err_class, 'None')
    print('Error Number: %s' % (err_num))
    print('Error Type: %s' % (err_class))
    print('Error Message: %s' % (err_msg))

try:
    import ogr
    import osr
    import gdal
    version_num = int(gdal.VersionInfo('VERSION_NUM'))
    if version_num >= 2000000:
        has_ogr = True
        gdal.PushErrorHandler(gdal_error_handler)
    else:
        print('GDAL version >= 2.0 is required:')
        has_ogr = False
except Exception as e:
    print('GDAL is not available:')
    print(e)
    has_ogr = False

class TestRun(unittest.TestCase):
    """Tests for (non-scalar) LagrangianArray"""

    def make_OceanDrift_object(self):
        self.o = OceanDrift(loglevel=30)
        self.fake_eddy = reader_ArtificialOceanEddy.Reader(2, 62)
        self.o.use_block = False
        self.reader_basemap = reader_basemap_landmask.Reader(