Пример #1
0
def test_identify_1():

    file_list = gdal.ReadDir('data')

    dr = gdal.IdentifyDriver('data/byte.tif', file_list)
    assert dr is not None and dr.GetDescription() == 'GTiff', \
        'Got wrong driver for byte.tif'
Пример #2
0
def netcdf_18():

    if gdaltest.netcdf_drv is None:
        return 'skip'

    ifile = 'data/trmm-nc4c.nc'

    if gdaltest.netcdf_drv_has_nc4:

        # test with Open()
        ds = gdal.Open(ifile)
        if ds is None:
            return 'fail'
        else:
            name = ds.GetDriver().GetDescription()
            ds = None
            #return fail if did not open with the netCDF driver (i.e. HDF5Image)
            if name != 'netCDF':
                return 'fail'

        # test with Identify()
        name = gdal.IdentifyDriver(ifile).GetDescription()
        if name != 'netCDF':
            return 'fail'

    else:
        return 'skip'

    return 'success'
Пример #3
0
def isRaster(source):
    """
    Test if loadRaster fails for the given input

    Parameters:
    -----------
    source : str
        The path to the raster file to load

    Returns:
    --------
    bool -> True if the given input is a raster

    """
    if isinstance(source, gdal.Dataset):
        try:
            if source.GetLayerCount() == 0:
                return True  # This should always be true?
            else:
                return False
        except:
            return False
    elif isinstance(source, str):
        d = gdal.IdentifyDriver(source)

        meta = d.GetMetadata()
        if meta.get("DCAP_RASTER", False) == "YES": return True
        else: return False
    else:
        return False
Пример #4
0
def isVector(source):
    """
    Test if loadVector fails for the given input

    Parameters:
    -----------
    source : str
        The path to the vector file to load

    Returns:
    --------
    bool -> True if the given input is a vector

    """

    if isinstance(source, gdal.Dataset):
        if source.GetLayerCount() > 0: return True
        else: return False
    elif isinstance(source, str):
        d = gdal.IdentifyDriver(source)

        meta = d.GetMetadata()
        if meta.get("DCAP_VECTOR", False) == "YES": return True
        else: return False
    else:
        return False
Пример #5
0
def netcdf_23():

    #don't skip if netcdf is not enabled in GDAL
    #if gdaltest.netcdf_drv is None:
    #    return 'skip'
    #if not gdaltest.netcdf_drv_has_hdf4:
    #    return 'skip'

    #skip test if Hdf4 is not enabled in GDAL
    if gdal.GetDriverByName( 'HDF4' ) is None and \
            gdal.GetDriverByName( 'HDF4Image' ) is None:
        return 'skip'

    ifile = 'data/hdifftst2.hdf'

    #test with Open()
    ds = gdal.Open(ifile)
    if ds is None:
        gdaltest.post_reason('GDAL did not open hdf4 file')
        return 'fail'
    else:
        name = ds.GetDriver().GetDescription()
        ds = None
        #return fail if opened with the netCDF driver
        if name == 'netCDF':
            gdaltest.post_reason('netcdf driver opened hdf4 file')
            return 'fail'

    # test with Identify()
    name = gdal.IdentifyDriver(ifile).GetDescription()
    if name == 'netCDF':
        gdaltest.post_reason('netcdf driver was identified for hdf4 file')
        return 'fail'

    return 'success'
Пример #6
0
def identify_3():

    dr = gdal.IdentifyDriver( 'data' )
    if dr is not None:
        gdaltest.post_reason( 'Got a driver for data directory!' )
        return 'fail'

    return 'success'
Пример #7
0
def identify_2():

    file_list = gdal.ReadDir( 'data' )

    dr = gdal.IdentifyDriver( 'data/byte.pnm.aux.xml', file_list )
    if dr is not None:
        gdaltest.post_reason( 'Got a driver for byte.pnm.aux.xml!' )
        return 'fail'

    return 'success'
Пример #8
0
def identify_1():

    file_list = gdal.ReadDir( 'data' )

    dr = gdal.IdentifyDriver( 'data/byte.tif', file_list )
    if dr is None or dr.GetDescription() != 'GTiff':
        gdaltest.post_reason( 'Got wrong driver for byte.tif' )
        return 'fail'

    return 'success'
Пример #9
0
def ProcessTarget(target, recursive, report_failure, filelist=None):
    if filelist is not None:
        driver = gdal.IdentifyDriver(target, filelist)
    else:
        driver = gdal.IdentifyDriver(target)

    if driver is not None:
        print('%s: %s' % (target, driver.ShortName))
    elif report_failure:
        print('%s: unrecognized' % target)

    if recursive and driver is None:
        try:
            mode = os.stat(target)[stat.ST_MODE]
        except OSError:
            mode = 0

        if stat.S_ISDIR(mode):
            subfilelist = os.listdir(target)
            for item in subfilelist:
                subtarget = os.path.join(target, item)
                ProcessTarget(subtarget, 1, report_failure, subfilelist)
Пример #10
0
    def cleanup(self):
        """
        Remove temporary file(s) and close dataset

        """
        if os.path.exists(self.temp_image):
            self.rasterDS = None
            drvr = gdal.IdentifyDriver(self.temp_image)
            drvr.Delete(self.temp_image)

        del self.layer
        self.layer = None
        del self.ds
        self.ds = None
        if hasattr(self, 'reprojectedFile'):
            drvr = self.reprojectedDS.GetDriver()
            delattr(self, 'reprojectedDS')
            drvr.DeleteDataSource(self.reprojectedFile)
            delattr(self, 'reprojectedFile')
Пример #11
0
def netcdf_17():

    if gdaltest.netcdf_drv is None:
        return 'skip'

    ifile = 'data/groups.h5'

    #skip test if Hdf5 is not enabled
    if gdal.GetDriverByName( 'HDF5' ) is None and \
            gdal.GetDriverByName( 'HDF5Image' ) is None:
        return 'skip'

    if gdaltest.netcdf_drv_has_nc4:

        #test with Open()
        ds = gdal.Open(ifile)
        if ds is None:
            gdaltest.post_reason('GDAL did not open hdf5 file')
            return 'fail'
        else:
            name = ds.GetDriver().GetDescription()
            ds = None
            #return fail if opened with the netCDF driver
            if name == 'netCDF':
                gdaltest.post_reason('netcdf driver opened hdf5 file')
                return 'fail'

        # test with Identify()
        name = gdal.IdentifyDriver(ifile).GetDescription()
        if name == 'netCDF':
            gdaltest.post_reason('netcdf driver was identified for hdf5 file')
            return 'fail'

    else:
        return 'skip'

    return 'success'
Пример #12
0
 def validate(self, filename, **kwargs):
     if gdal.IdentifyDriver(filename) is None:
         return False
     return True
Пример #13
0
# =============================================================================

src_ds = gdal.Open(src_filename)

if src_ds is None:
    print('Unable to open %s' % src_filename)
    sys.exit(1)

srcband = src_ds.GetRasterBand(src_band_n)

# =============================================================================
#       Try opening the destination file as an existing file.
# =============================================================================

try:
    driver = gdal.IdentifyDriver(dst_filename)
    if driver is not None:
        dst_ds = gdal.Open(dst_filename, gdal.GA_Update)
        dstband = dst_ds.GetRasterBand(dst_band_n)
    else:
        dst_ds = None
except:
    dst_ds = None

# =============================================================================
#     Create output file.
# =============================================================================
if dst_ds is None:
    if format is None:
        format = GetOutputDriverFor(dst_filename)
Пример #14
0
def main():
    """
    Main routine
    """
    cmdargs = getCmdargs()

    errorStatus = 0

    truesegfile = "tmp_trueseg.kea"
    if cmdargs.knownseg is not None:
        truesegfile = cmdargs.knownseg
    imagefile = "tmp_image.kea"
    outsegfile = "tmp_seg.kea"
    tmpdatafiles = [imagefile, outsegfile]
    if cmdargs.knownseg is None:
        tmpdatafiles.append(truesegfile)

    if cmdargs.knownseg is None:
        print("Generating known segmentation {}".format(truesegfile))
        generateTrueSegments(truesegfile)
    print("Creating known multi-spectral image {}".format(imagefile))
    createMultispectral(truesegfile, imagefile)

    # Ensure enough clusters that we have a different cluster for each
    # segment in the generated image. We have not guarded against neighbours
    # being similar, so this will prevent neighbouring segments being
    # merged too easily.
    numClusters = len(initialCentres)

    print("Doing tiled segmentation, creating {}".format(outsegfile))
    # Note that we use fourConnected=False, to avoid disconnecting the
    # pointy ends of long thin slivers, which can arise due to how we
    # generated the original segments.
    segResults = tiling.doTiledShepherdSegmentation(imagefile,
                                                    outsegfile,
                                                    numClusters=numClusters,
                                                    fixedKMeansInit=True,
                                                    fourConnected=False)

    (meanColNames, stdColNames) = makeRATcolumns(segResults, outsegfile,
                                                 imagefile)

    pcntMatch = checkSegmentation(imagefile, outsegfile, meanColNames,
                                  stdColNames)

    print("Segment match on {}% of pixels".format(pcntMatch))
    if pcntMatch < 100:
        print(
            "Matching on less than 100% suggests that the segmentation went wrong"
        )
        errorStatus = 1

    print("Adding colour table to {}".format(outsegfile))
    utils.writeColorTableFromRatColumns(outsegfile, meanColNames[0],
                                        meanColNames[1], meanColNames[2])

    if not cmdargs.keep:
        print("Removing generated data")
        for fn in tmpdatafiles:
            drvr = gdal.IdentifyDriver(fn)
            drvr.Delete(fn)

    # Exit with an explicit status code, so that Github workflow
    # can recognise if something went wrong.
    sys.exit(errorStatus)
Пример #15
0
def test_identify_2():

    file_list = gdal.ReadDir('data')

    dr = gdal.IdentifyDriver('data/byte.pnm.aux.xml', file_list)
    assert dr is None, 'Got a driver for byte.pnm.aux.xml!'
Пример #16
0
def gdal_proximity(
    src_filename: Optional[str] = None,
    src_band_n: int = 1,
    dst_filename: Optional[str] = None,
    dst_band_n: int = 1,
    driver_name: Optional[str] = None,
    creation_type: str = 'Float32',
    creation_options: Optional[Sequence[str]] = None,
    alg_options: Optional[Sequence[str]] = None,
    quiet: bool = False):

    # =============================================================================
    #    Open source file
    # =============================================================================
    creation_options = creation_options or []
    alg_options = alg_options or []
    src_ds = gdal.Open(src_filename)

    if src_ds is None:
        print('Unable to open %s' % src_filename)
        return 1

    srcband = src_ds.GetRasterBand(src_band_n)

    # =============================================================================
    #       Try opening the destination file as an existing file.
    # =============================================================================

    try:
        driver_name = gdal.IdentifyDriver(dst_filename)
        if driver_name is not None:
            dst_ds = gdal.Open(dst_filename, gdal.GA_Update)
            dstband = dst_ds.GetRasterBand(dst_band_n)
        else:
            dst_ds = None
    except:
        dst_ds = None

    # =============================================================================
    #     Create output file.
    # =============================================================================
    if dst_ds is None:
        if driver_name is None:
            driver_name = GetOutputDriverFor(dst_filename)

        drv = gdal.GetDriverByName(driver_name)
        dst_ds = drv.Create(dst_filename,
                            src_ds.RasterXSize, src_ds.RasterYSize, 1,
                            gdal.GetDataTypeByName(creation_type), creation_options)

        dst_ds.SetGeoTransform(src_ds.GetGeoTransform())
        dst_ds.SetProjection(src_ds.GetProjectionRef())

        dstband = dst_ds.GetRasterBand(1)

    # =============================================================================
    #    Invoke algorithm.
    # =============================================================================

    if quiet:
        prog_func = None
    else:
        prog_func = gdal.TermProgress_nocb

    gdal.ComputeProximity(srcband, dstband, alg_options,
                          callback=prog_func)

    srcband = None
    dstband = None
    src_ds = None
    dst_ds = None
Пример #17
0
def gdal_api_proxy_sub():

    src_ds = gdal.Open('data/byte.tif')
    src_cs = src_ds.GetRasterBand(1).Checksum()
    src_gt = src_ds.GetGeoTransform()
    src_prj = src_ds.GetProjectionRef()
    src_data = src_ds.ReadRaster(0, 0, 20, 20)
    src_md = src_ds.GetMetadata()
    src_ds = None

    drv = gdal.IdentifyDriver('data/byte.tif')
    if drv.GetDescription() != 'API_PROXY':
        gdaltest.post_reason('fail')
        return 'fail'

    ds = gdal.GetDriverByName('GTiff').Create('tmp/byte.tif', 1, 1, 3)
    ds = None

    src_ds = gdal.Open('data/byte.tif')
    ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/byte.tif',
                                                  src_ds,
                                                  options=['TILED=YES'])
    got_cs = ds.GetRasterBand(1).Checksum()
    if src_cs != got_cs:
        gdaltest.post_reason('fail')
        return 'fail'
    ds = None

    ds = gdal.Open('tmp/byte.tif', gdal.GA_Update)

    ds.SetGeoTransform([1, 2, 3, 4, 5, 6])
    got_gt = ds.GetGeoTransform()
    if src_gt == got_gt:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.SetGeoTransform(src_gt)
    got_gt = ds.GetGeoTransform()
    if src_gt != got_gt:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetGCPCount() != 0:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetGCPProjection() != '':
        print(ds.GetGCPProjection())
        gdaltest.post_reason('fail')
        return 'fail'

    if len(ds.GetGCPs()) != 0:
        gdaltest.post_reason('fail')
        return 'fail'

    gcps = [gdal.GCP(0, 1, 2, 3, 4)]
    ds.SetGCPs(gcps, "foo")

    got_gcps = ds.GetGCPs()
    if len(got_gcps) != 1:
        gdaltest.post_reason('fail')
        return 'fail'

    if got_gcps[0].GCPLine != gcps[0].GCPLine or  \
       got_gcps[0].GCPPixel != gcps[0].GCPPixel or  \
       got_gcps[0].GCPX != gcps[0].GCPX or \
       got_gcps[0].GCPY != gcps[0].GCPY:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetGCPProjection() != 'foo':
        gdaltest.post_reason('fail')
        print(ds.GetGCPProjection())
        return 'fail'

    ds.SetGCPs([], "")

    if len(ds.GetGCPs()) != 0:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.SetProjection('')
    got_prj = ds.GetProjectionRef()
    if src_prj == got_prj:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.SetProjection(src_prj)
    got_prj = ds.GetProjectionRef()
    if src_prj != got_prj:
        gdaltest.post_reason('fail')
        print(src_prj)
        print(got_prj)
        return 'fail'

    ds.GetRasterBand(1).Fill(0)
    got_cs = ds.GetRasterBand(1).Checksum()
    if 0 != got_cs:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).WriteRaster(0, 0, 20, 20, src_data)
    got_cs = ds.GetRasterBand(1).Checksum()
    if src_cs != got_cs:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).Fill(0)
    got_cs = ds.GetRasterBand(1).Checksum()
    if 0 != got_cs:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.WriteRaster(0, 0, 20, 20, src_data)
    got_cs = ds.GetRasterBand(1).Checksum()
    if src_cs != got_cs:
        gdaltest.post_reason('fail')
        return 'fail'

    # Not bound to SWIG
    # ds.AdviseRead(0,0,20,20,20,20)

    got_data = ds.ReadRaster(0, 0, 20, 20)
    if src_data != got_data:
        gdaltest.post_reason('fail')
        return 'fail'

    got_data = ds.GetRasterBand(1).ReadRaster(0, 0, 20, 20)
    if src_data != got_data:
        gdaltest.post_reason('fail')
        return 'fail'

    got_data_weird_spacing = ds.ReadRaster(0,
                                           0,
                                           20,
                                           20,
                                           buf_pixel_space=1,
                                           buf_line_space=32)
    if len(got_data_weird_spacing) != 32 * (20 - 1) + 20:
        gdaltest.post_reason('fail')
        print(len(got_data_weird_spacing))
        return 'fail'

    if got_data[20:20 + 20] != got_data_weird_spacing[32:32 + 20]:
        gdaltest.post_reason('fail')
        return 'fail'

    got_data_weird_spacing = ds.GetRasterBand(1).ReadRaster(0,
                                                            0,
                                                            20,
                                                            20,
                                                            buf_pixel_space=1,
                                                            buf_line_space=32)
    if len(got_data_weird_spacing) != 32 * (20 - 1) + 20:
        gdaltest.post_reason('fail')
        print(len(got_data_weird_spacing))
        return 'fail'

    if got_data[20:20 + 20] != got_data_weird_spacing[32:32 + 20]:
        gdaltest.post_reason('fail')
        return 'fail'

    got_block = ds.GetRasterBand(1).ReadBlock(0, 0)
    if len(got_block) != 256 * 256:
        gdaltest.post_reason('fail')
        return 'fail'

    if got_data[20:20 + 20] != got_block[256:256 + 20]:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.FlushCache()
    ds.GetRasterBand(1).FlushCache()

    got_data = ds.GetRasterBand(1).ReadRaster(0, 0, 20, 20)
    if src_data != got_data:
        gdaltest.post_reason('fail')
        return 'fail'

    if len(ds.GetFileList()) != 1:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.AddBand(gdal.GDT_Byte) == 0:
        gdaltest.post_reason('fail')
        return 'fail'

    got_md = ds.GetMetadata()
    if src_md != got_md:
        gdaltest.post_reason('fail')
        print(src_md)
        print(got_md)
        return 'fail'

    if ds.GetMetadataItem('AREA_OR_POINT') != 'Area':
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetMetadataItem('foo') is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.SetMetadataItem('foo', 'bar')
    if ds.GetMetadataItem('foo') != 'bar':
        gdaltest.post_reason('fail')
        return 'fail'

    ds.SetMetadata({'foo': 'baz'}, 'OTHER')
    if ds.GetMetadataItem('foo', 'OTHER') != 'baz':
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).SetMetadata({'foo': 'baw'}, 'OTHER')
    if ds.GetRasterBand(1).GetMetadataItem('foo', 'OTHER') != 'baw':
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetMetadataItem('INTERLEAVE', 'IMAGE_STRUCTURE') != 'BAND':
        gdaltest.post_reason('fail')
        return 'fail'

    if len(ds.GetRasterBand(1).GetMetadata()) != 0:
        gdaltest.post_reason('fail')
        print(ds.GetRasterBand(1).GetMetadata())
        return 'fail'

    if ds.GetRasterBand(1).GetMetadataItem('foo') is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).SetMetadataItem('foo', 'baz')
    if ds.GetRasterBand(1).GetMetadataItem('foo') != 'baz':
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).SetMetadata({'foo': 'baw'})
    if ds.GetRasterBand(1).GetMetadataItem('foo') != 'baw':
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).GetColorInterpretation() != gdal.GCI_GrayIndex:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_Undefined)

    ct = ds.GetRasterBand(1).GetColorTable()
    if ct is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    ct = gdal.ColorTable()
    ct.SetColorEntry(0, (1, 2, 3))
    if ds.GetRasterBand(1).SetColorTable(ct) != 0:
        gdaltest.post_reason('fail')
        return 'fail'

    ct = ds.GetRasterBand(1).GetColorTable()
    if ct is None:
        gdaltest.post_reason('fail')
        return 'fail'
    if ct.GetColorEntry(0) != (1, 2, 3, 255):
        gdaltest.post_reason('fail')
        return 'fail'

    ct = ds.GetRasterBand(1).GetColorTable()
    if ct is None:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).SetColorTable(None) != 0:
        gdaltest.post_reason('fail')
        return 'fail'

    ct = ds.GetRasterBand(1).GetColorTable()
    if ct is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    rat = ds.GetRasterBand(1).GetDefaultRAT()
    if rat is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).SetDefaultRAT(None) != 0:
        gdaltest.post_reason('fail')
        return 'fail'

    ref_rat = gdal.RasterAttributeTable()
    if ds.GetRasterBand(1).SetDefaultRAT(ref_rat) != 0:
        gdaltest.post_reason('fail')
        return 'fail'

    rat = ds.GetRasterBand(1).GetDefaultRAT()
    if rat is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).SetDefaultRAT(None) != 0:
        gdaltest.post_reason('fail')
        return 'fail'

    rat = ds.GetRasterBand(1).GetDefaultRAT()
    if rat is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).GetMinimum() is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    got_stats = ds.GetRasterBand(1).GetStatistics(0, 0)
    if got_stats[3] >= 0.0:
        gdaltest.post_reason('fail')
        return 'fail'

    got_stats = ds.GetRasterBand(1).GetStatistics(1, 1)
    if got_stats[0] != 74.0:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).GetMinimum() != 74.0:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).GetMaximum() != 255.0:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).SetStatistics(1, 2, 3, 4)
    got_stats = ds.GetRasterBand(1).GetStatistics(1, 1)
    if got_stats != [1, 2, 3, 4]:
        print(got_stats)
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).ComputeStatistics(0)
    got_stats = ds.GetRasterBand(1).GetStatistics(1, 1)
    if got_stats[0] != 74.0:
        gdaltest.post_reason('fail')
        return 'fail'

    minmax = ds.GetRasterBand(1).ComputeRasterMinMax()
    if minmax != (74.0, 255.0):
        gdaltest.post_reason('fail')
        print(minmax)
        return 'fail'

    if ds.GetRasterBand(1).GetOffset() != 0.0:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).GetScale() != 1.0:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).SetOffset(10.0)
    if ds.GetRasterBand(1).GetOffset() != 10.0:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).SetScale(2.0)
    if ds.GetRasterBand(1).GetScale() != 2.0:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.BuildOverviews('NEAR', [2])
    if ds.GetRasterBand(1).GetOverviewCount() != 1:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).GetOverview(-1) is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).GetOverview(0) is None:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).GetOverview(0) is None:
        gdaltest.post_reason('fail')
        return 'fail'

    got_hist = ds.GetRasterBand(1).GetHistogram()
    if len(got_hist) != 256:
        gdaltest.post_reason('fail')
        return 'fail'

    (minval, maxval, nitems,
     got_hist2) = ds.GetRasterBand(1).GetDefaultHistogram()
    if minval != -0.5:
        gdaltest.post_reason('fail')
        return 'fail'
    if maxval != 255.5:
        gdaltest.post_reason('fail')
        return 'fail'
    if nitems != 256:
        gdaltest.post_reason('fail')
        return 'fail'
    if got_hist != got_hist2:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).SetDefaultHistogram(1, 2, [3])
    (minval, maxval, nitems,
     got_hist3) = ds.GetRasterBand(1).GetDefaultHistogram()
    if minval != 1:
        gdaltest.post_reason('fail')
        return 'fail'
    if maxval != 2:
        gdaltest.post_reason('fail')
        return 'fail'
    if nitems != 1:
        gdaltest.post_reason('fail')
        return 'fail'
    if got_hist3[0] != 3:
        gdaltest.post_reason('fail')
        return 'fail'

    got_nodatavalue = ds.GetRasterBand(1).GetNoDataValue()
    if got_nodatavalue is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).SetNoDataValue(123)
    got_nodatavalue = ds.GetRasterBand(1).GetNoDataValue()
    if got_nodatavalue != 123:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).GetMaskFlags() != 8:
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).GetMaskBand() is None:
        gdaltest.post_reason('fail')
        return 'fail'

    ret = ds.GetRasterBand(1).DeleteNoDataValue()
    if ret != 0:
        gdaltest.post_reason('fail')
        return 'fail'
    got_nodatavalue = ds.GetRasterBand(1).GetNoDataValue()
    if got_nodatavalue is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.CreateMaskBand(0)

    if ds.GetRasterBand(1).GetMaskFlags() != 2:
        print(ds.GetRasterBand(1).GetMaskFlags())
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).GetMaskBand() is None:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).CreateMaskBand(0)

    if ds.GetRasterBand(1).HasArbitraryOverviews() != 0:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).SetUnitType('foo')
    if ds.GetRasterBand(1).GetUnitType() != 'foo':
        gdaltest.post_reason('fail')
        return 'fail'

    if ds.GetRasterBand(1).GetCategoryNames() is not None:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).SetCategoryNames(['foo'])
    if ds.GetRasterBand(1).GetCategoryNames() != ['foo']:
        gdaltest.post_reason('fail')
        return 'fail'

    ds.GetRasterBand(1).SetDescription('bar')

    ds = None

    gdal.GetDriverByName('GTiff').Delete('tmp/byte.tif')

    return 'success'
Пример #18
0
def main(argv):
    frmt = None
    creation_options = []
    options = []
    src_filename = None
    src_band_n = 1
    dst_filename = None
    dst_band_n = 1
    creation_type = 'Float32'
    quiet_flag = 0

    gdal.AllRegister()
    argv = gdal.GeneralCmdLineProcessor(argv)
    if argv is None:
        sys.exit(0)

    # Parse command line arguments.
    i = 1
    while i < len(argv):
        arg = argv[i]

        if arg == '-of' or arg == '-f':
            i = i + 1
            frmt = argv[i]

        elif arg == '-co':
            i = i + 1
            creation_options.append(argv[i])

        elif arg == '-ot':
            i = i + 1
            creation_type = argv[i]

        elif arg == '-maxdist':
            i = i + 1
            options.append('MAXDIST=' + argv[i])

        elif arg == '-values':
            i = i + 1
            options.append('VALUES=' + argv[i])

        elif arg == '-distunits':
            i = i + 1
            options.append('DISTUNITS=' + argv[i])

        elif arg == '-nodata':
            i = i + 1
            options.append('NODATA=' + argv[i])

        elif arg == '-use_input_nodata':
            i = i + 1
            options.append('USE_INPUT_NODATA=' + argv[i])

        elif arg == '-fixed-buf-val':
            i = i + 1
            options.append('FIXED_BUF_VAL=' + argv[i])

        elif arg == '-srcband':
            i = i + 1
            src_band_n = int(argv[i])

        elif arg == '-dstband':
            i = i + 1
            dst_band_n = int(argv[i])

        elif arg == '-q' or arg == '-quiet':
            quiet_flag = 1

        elif src_filename is None:
            src_filename = argv[i]

        elif dst_filename is None:
            dst_filename = argv[i]

        else:
            Usage()

        i = i + 1

    if src_filename is None or dst_filename is None:
        Usage()

    # =============================================================================
    #    Open source file
    # =============================================================================

    src_ds = gdal.Open(src_filename)

    if src_ds is None:
        print('Unable to open %s' % src_filename)
        sys.exit(1)

    srcband = src_ds.GetRasterBand(src_band_n)

    # =============================================================================
    #       Try opening the destination file as an existing file.
    # =============================================================================

    try:
        driver = gdal.IdentifyDriver(dst_filename)
        if driver is not None:
            dst_ds = gdal.Open(dst_filename, gdal.GA_Update)
            dstband = dst_ds.GetRasterBand(dst_band_n)
        else:
            dst_ds = None
    except:
        dst_ds = None

    # =============================================================================
    #     Create output file.
    # =============================================================================
    if dst_ds is None:
        if frmt is None:
            frmt = GetOutputDriverFor(dst_filename)

        drv = gdal.GetDriverByName(frmt)
        dst_ds = drv.Create(dst_filename, src_ds.RasterXSize,
                            src_ds.RasterYSize, 1,
                            gdal.GetDataTypeByName(creation_type),
                            creation_options)

        dst_ds.SetGeoTransform(src_ds.GetGeoTransform())
        dst_ds.SetProjection(src_ds.GetProjectionRef())

        dstband = dst_ds.GetRasterBand(1)

    # =============================================================================
    #    Invoke algorithm.
    # =============================================================================

    if quiet_flag:
        prog_func = None
    else:
        prog_func = gdal.TermProgress_nocb

    gdal.ComputeProximity(srcband, dstband, options, callback=prog_func)

    srcband = None
    dstband = None
    src_ds = None
    dst_ds = None
Пример #19
0
def main_loop():

    server_ds = None
    server_bands = []
    gdal.SetConfigOption('GDAL_API_PROXY', 'NO')

    while 1:
        sys.stdout.flush()

        instr = read_int()
        if VERBOSE:
            sys.stderr.write('instr=%d\n' % instr)

        band = None
        if instr >= INSTR_Band_First and instr <= INSTR_Band_End:
            srv_band = read_int()
            band = server_bands[srv_band]

        if instr == INSTR_GetGDALVersion:
            if sys.version_info >= (3, 0, 0):
                lsb = struct.unpack('B', sys.stdin.read(1).encode('latin1'))[0]
            else:
                lsb = struct.unpack('B', sys.stdin.read(1))[0]
            ver = read_str()
            vmajor = read_int()
            vminor = read_int()
            protovmajor = read_int()
            protovminor = read_int()
            extra_bytes = read_int()
            if VERBOSE:
                sys.stderr.write('lsb=%d\n' % lsb)
                sys.stderr.write('ver=%s\n' % ver)
                sys.stderr.write('vmajor=%d\n' % vmajor)
                sys.stderr.write('vminor=%d\n' % vminor)
                sys.stderr.write('protovmajor=%d\n' % protovmajor)
                sys.stderr.write('protovminor=%d\n' % protovminor)
                sys.stderr.write('extra_bytes=%d\n' % extra_bytes)

            write_str('2.1dev')
            write_int(2)  # vmajor
            write_int(1)  # vminor
            write_int(3)  # protovmajor
            write_int(0)  # protovminor
            write_int(0)  # extra bytes
            continue
        elif instr == INSTR_EXIT:
            server_ds = None
            server_bands = []
            write_marker()
            write_int(1)
            sys.exit(0)
        elif instr == INSTR_EXIT_FAIL:
            server_ds = None
            server_bands = []
            write_marker()
            write_int(1)
            sys.exit(1)
        elif instr == INSTR_SetConfigOption:
            key = read_str()
            val = read_str()
            gdal.SetConfigOption(key, val)
            if VERBOSE:
                sys.stderr.write('key=%s\n' % key)
                sys.stderr.write('val=%s\n' % val)
            continue
        elif instr == INSTR_Reset:
            # if server_ds is not None:
            #    sys.stderr.write('Reset(%s)\n' % server_ds.GetDescription())
            server_ds = None
            server_bands = []
            write_marker()
            write_int(1)
        elif instr == INSTR_Open:
            access = read_int()
            filename = read_str()
            cwd = read_str()
            open_options = read_strlist()
            if cwd is not None:
                os.chdir(cwd)
            if VERBOSE:
                sys.stderr.write('access=%d\n' % access)
                sys.stderr.write('filename=%s\n' % filename)
                sys.stderr.write('cwd=%s\n' % cwd)
                sys.stderr.write('open_options=%s\n' % str(open_options))
            # sys.stderr.write('Open(%s)\n' % filename)
            try:
                server_ds = GDALPythonServerDataset(filename, access, open_options)
            except:
                server_ds = None

            write_marker()
            if server_ds is None:
                write_int(0)  # Failure
            else:
                write_int(1)  # Success
                write_int(16)  # caps length
                caps = [0 for i in range(16)]
                for cap in caps_list:
                    caps[int(cap / 8)] = caps[int(cap / 8)] | (1 << (cap % 8))
                for i in range(16):
                    sys.stdout.write(struct.pack('B', caps[i]))  # caps
                write_str(server_ds.GetDescription())
                drv = server_ds.GetDriver()
                if drv is not None:
                    write_str(drv.GetDescription())
                    write_int(0)  # End of driver metadata
                else:
                    write_str(None)
                write_int(server_ds.RasterXSize)  # X
                write_int(server_ds.RasterYSize)  # Y
                write_int(server_ds.RasterCount)  # Band count
                write_int(1)  # All bands are identical

                if server_ds.RasterCount > 0:
                    write_band(server_ds.GetRasterBand(1), len(server_bands))
                    for i in range(server_ds.RasterCount):
                        server_bands.append(server_ds.GetRasterBand(i + 1))
        elif instr == INSTR_Identify:
            filename = read_str()
            cwd = read_str()
            dr = gdal.IdentifyDriver(filename)
            write_marker()
            if dr is None:
                write_int(0)
            else:
                write_int(1)
        elif instr == INSTR_Create:
            filename = read_str()
            cwd = read_str()
            read_int()  # xsize =
            read_int()  # ysize =
            read_int()  # bands =
            read_int()  # datatype =
            read_strlist()  # options =
            write_marker()
            # FIXME
            write_int(0)
        elif instr == INSTR_CreateCopy:
            filename = read_str()
            read_str()  # src_description =
            cwd = read_str()
            read_int()  # strict =
            read_strlist()  # options =
            # FIXME
            write_int(0)
        elif instr == INSTR_QuietDelete:
            filename = read_str()
            cwd = read_str()
            write_marker()
            # FIXME
        elif instr == INSTR_GetGeoTransform:
            gt = server_ds.GetGeoTransform()
            write_marker()
            if gt is not None:
                write_int(CE_None)
                write_int(6 * 8)
                for i in range(6):
                    write_double(gt[i])
            else:
                write_int(CE_Failure)
        elif instr == INSTR_GetProjectionRef:
            write_marker()
            write_str(server_ds.GetProjectionRef())
        elif instr == INSTR_GetGCPCount:
            write_marker()
            write_int(server_ds.GetGCPCount())
        elif instr == INSTR_GetFileList:
            write_marker()
            fl = server_ds.GetFileList()
            write_int(len(fl))
            for f in fl:
                write_str(f)
        elif instr == INSTR_GetMetadata:
            domain = read_str()
            md = server_ds.GetMetadata(domain)
            write_marker()
            write_int(len(md))
            for key in md:
                write_str('%s=%s' % (key, md[key]))
        elif instr == INSTR_GetMetadataItem:
            key = read_str()
            domain = read_str()
            val = server_ds.GetMetadataItem(key, domain)
            write_marker()
            write_str(val)
        elif instr == INSTR_IRasterIO_Read:
            nXOff = read_int()
            nYOff = read_int()
            nXSize = read_int()
            nYSize = read_int()
            nBufXSize = read_int()
            nBufYSize = read_int()
            nBufType = read_int()
            nBandCount = read_int()
            panBandMap = []
            read_int()  # size =
            for i in range(nBandCount):
                panBandMap.append(read_int())
            nPixelSpace = read_bigint()
            nLineSpace = read_bigint()
            nBandSpace = read_bigint()
            val = server_ds.IRasterIO_Read(nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize, nBufType, panBandMap, nPixelSpace, nLineSpace, nBandSpace)
            write_marker()
            if val is None:
                write_int(CE_Failure)
                write_int(0)
            else:
                write_int(CE_None)
                write_int(len(val))
                sys.stdout.write(val)
        elif instr == INSTR_FlushCache:
            if server_ds is not None:
                server_ds.FlushCache()
            write_marker()
        elif instr == INSTR_Band_FlushCache:
            val = band.FlushCache()
            write_marker()
            write_int(val)
        elif instr == INSTR_Band_GetCategoryNames:
            write_marker()
            # FIXME
            write_int(-1)
        elif instr == INSTR_Band_GetMetadata:
            domain = read_str()
            md = band.GetMetadata(domain)
            write_marker()
            write_int(len(md))
            for key in md:
                write_str('%s=%s' % (key, md[key]))
        elif instr == INSTR_Band_GetMetadataItem:
            key = read_str()
            domain = read_str()
            val = band.GetMetadataItem(key, domain)
            write_marker()
            write_str(val)
        elif instr == INSTR_Band_GetColorInterpretation:
            val = band.GetColorInterpretation()
            write_marker()
            write_int(val)
        elif instr == INSTR_Band_GetNoDataValue:
            val = band.GetNoDataValue()
            write_marker()
            if val is None:
                write_int(0)
                write_double(0)
            else:
                write_int(1)
                write_double(val)
        elif instr == INSTR_Band_GetMinimum:
            val = band.GetMinimum()
            write_marker()
            if val is None:
                write_int(0)
                write_double(0)
            else:
                write_int(1)
                write_double(val)
        elif instr == INSTR_Band_GetMaximum:
            val = band.GetMaximum()
            write_marker()
            if val is None:
                write_int(0)
                write_double(0)
            else:
                write_int(1)
                write_double(val)
        elif instr == INSTR_Band_GetOffset:
            val = band.GetOffset()
            write_marker()
            if val is None:
                write_int(0)
                write_double(0)
            else:
                write_int(1)
                write_double(val)
        elif instr == INSTR_Band_GetScale:
            val = band.GetScale()
            write_marker()
            if val is None:
                write_int(0)
                write_double(1)  # default value is 1
            else:
                write_int(1)
                write_double(val)
        elif instr == INSTR_Band_IReadBlock:
            nXBlockOff = read_int()
            nYBlockOff = read_int()
            val = band.IReadBlock(nXBlockOff, nYBlockOff)
            write_marker()
            if val is None:
                write_int(CE_Failure)
                length = band.BlockXSize * band.BlockYSize * (gdal.GetDataTypeSize(band.DataType) / 8)
                write_int(length)
                sys.stdout.write(''.join('\0' for i in range(length)))
            else:
                write_int(CE_None)
                write_int(len(val))
                sys.stdout.write(val)
        elif instr == INSTR_Band_IRasterIO_Read:
            nXOff = read_int()
            nYOff = read_int()
            nXSize = read_int()
            nYSize = read_int()
            nBufXSize = read_int()
            nBufYSize = read_int()
            nBufType = read_int()
            val = band.IRasterIO_Read(nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize, nBufType)
            write_marker()
            if val is None:
                write_int(CE_Failure)
                write_int(0)
            else:
                write_int(CE_None)
                write_int(len(val))
                sys.stdout.write(val)
        elif instr == INSTR_Band_GetStatistics:
            approx_ok = read_int()
            force = read_int()
            val = band.GetStatistics(approx_ok, force)
            write_marker()
            if val is None or val[3] < 0:
                write_int(CE_Failure)
            else:
                write_int(CE_None)
                write_double(val[0])
                write_double(val[1])
                write_double(val[2])
                write_double(val[3])
        elif instr == INSTR_Band_ComputeRasterMinMax:
            approx_ok = read_int()
            val = band.ComputeRasterMinMax(approx_ok)
            write_marker()
            if val is None:
                write_int(CE_Failure)
            else:
                write_int(CE_None)
                write_double(val[0])
                write_double(val[1])
        elif instr == INSTR_Band_GetHistogram:
            dfMin = read_double()
            dfMax = read_double()
            nBuckets = read_int()
            bIncludeOutOfRange = read_int()
            bApproxOK = read_int()
            val = band.GetHistogram(dfMin, dfMax, nBuckets, bIncludeOutOfRange, bApproxOK)
            write_marker()
            if val is None:
                write_int(CE_Failure)
            else:
                write_int(CE_None)
                write_int(len(val) * 8)
                for v in val:
                    write_uint64(v)
        # elif instr == INSTR_Band_GetDefaultHistogram:
        #    bForce = read_int()
        #    write_marker()
        #    write_int(CE_Failure)
        elif instr == INSTR_Band_HasArbitraryOverviews:
            val = band.HasArbitraryOverviews()
            write_marker()
            write_int(val)
        elif instr == INSTR_Band_GetOverviewCount:
            val = band.GetOverviewCount()
            write_marker()
            write_int(val)
        elif instr == INSTR_Band_GetOverview:
            iovr = read_int()
            ovr_band = band.GetOverview(iovr)
            write_marker()
            write_band(ovr_band, len(server_bands))
            if ovr_band is not None:
                server_bands.append(ovr_band)
        elif instr == INSTR_Band_GetMaskBand:
            msk_band = band.GetMaskBand()
            write_marker()
            write_band(msk_band, len(server_bands))
            if msk_band is not None:
                server_bands.append(msk_band)
        elif instr == INSTR_Band_GetMaskFlags:
            val = band.GetMaskFlags()
            write_marker()
            write_int(val)
        elif instr == INSTR_Band_GetColorTable:
            ct = band.GetColorTable()
            write_marker()
            write_ct(ct)
        elif instr == INSTR_Band_GetUnitType:
            val = band.GetUnitType()
            write_marker()
            write_str(val)
        # elif instr == INSTR_Band_GetDefaultRAT:
        #    write_marker()
        #    # FIXME
        #    write_int(0)
        else:
            break

        write_zero_error()
Пример #20
0
    #%% Set cmap if SCM
    if cmap_name.startswith('SCM'):
        if cmap_name.endswith('_r'):
            exec("cmap = {}.reversed()".format(cmap_name[:-2]))
        else:
            exec("cmap = {}".format(cmap_name))
    elif cmap_name == 'insar':
        cdict = tools_lib.cmap_insar()
        plt.register_cmap(
            cmap=mpl.colors.LinearSegmentedColormap('insar', cdict))
        cmap = 'insar'
    else:
        cmap = cmap_name

    #%% Get info and Read data
    if gdal.IdentifyDriver(infile):  ## If Geotiff or grd
        geotiff = gdal.Open(infile)
        data = geotiff.ReadAsArray()
        if data.ndim > 2:
            print('\nERROR: {} has multiple bands and cannot be displayed.\n'.
                  format(infile),
                  file=sys.stderr)
            sys.exit(2)

        length, width = data.shape
        lon_w_p, dlon, _, lat_n_p, _, dlat = geotiff.GetGeoTransform()
        lat_s_p = lat_n_p + dlat * length
        lon_e_p = lon_w_p + dlon * width
        if data.dtype == np.float32:
            data[data == nodata] = np.nan
Пример #21
0
def test_identify_3():

    dr = gdal.IdentifyDriver('data')
    assert dr is None, 'Got a driver for data directory!'
Пример #22
0
    def resampleToReference(self, ds, nullValList, workingRegion, resamplemethod, tempdir='.', useVRT=False):
        """
        Resamples any inputs that do not match the reference, to the 
        reference image. 
        
        ds is the GDAL dataset that needs to be resampled.
        nullValList is the list of null values for that dataset.
        workingRegion is a PixelGridDefn
        resamplemethod is a string containing a method supported by gdalwarp.
        
        Returns the new (temporary) resampled dataset instance.
        
        Do not call directly, use resampleAllToReference()
        
        """
    
        # get the name of the input file
        infile = ds.GetDescription()

        # create temporary .prf files with the source
        # and destination WKT strings.
        import tempfile
        # the src prf file
        (fileh,src_prf) = tempfile.mkstemp('.prf',dir=tempdir)
        fileobj = os.fdopen(fileh,'w')
        srcproj = self.specialProjFixes(ds.GetProjection())
        fileobj.write(srcproj)
        fileobj.close()
        
        # the dest prf file
        (fileh,dest_prf) = tempfile.mkstemp('.prf',dir=tempdir)
        fileobj = os.fdopen(fileh,'w')
        fileobj.write( self.referencePixGrid.projection)
        fileobj.close()

        if useVRT:
            ext = '.vrt'
        else:
            # get the driver from the input dataset
            # so we know the default extension, and type
            # for the temporary file.
            driver = gdal.IdentifyDriver(infile)
            drivermeta = driver.GetMetadata()
        
            # temp image file name - based on driver extension
            ext = ''
            if gdal.DMD_EXTENSION in drivermeta:
                ext = '.' + drivermeta[gdal.DMD_EXTENSION]

        (fileh,temp_image) = tempfile.mkstemp(ext,dir=tempdir)
        os.close(fileh)
          
        # build the command line for gdalwarp
        # as a list for subprocess - also a bit easier to read
        cmdList = [GDALWARP]
        
        # source projection prf file
        cmdList.append('-s_srs')
        cmdList.append(src_prf)
        
        # destination projection prf file
        cmdList.append('-t_srs')
        cmdList.append(dest_prf)
        
        # extent. Note the use of repr() to avoid loss of precision. 
        cmdList.append('-te')
        for x in [workingRegion.xMin, workingRegion.yMin, workingRegion.xMax, workingRegion.yMax]:
            cmdList.append(repr(x))
        
        # resolution. Note the use of repr() to avoid loss of precision. 
        cmdList.append('-tr')
        for x in [workingRegion.xRes, workingRegion.yRes]:
            cmdList.append(repr(x))
        
        # output format
        cmdList.append('-of')
        if useVRT:
            driverName = 'VRT'
        else:
            driverName = driver.ShortName
        cmdList.append(driverName)
        
        
        # resample method
        cmdList.append('-r')
        cmdList.append(resamplemethod)
        
        # null values
        nullOptions = self.makeWarpNullOptions(nullValList)
        if nullOptions is not None:
            cmdList.extend(nullOptions)
        
        # don't have creation options for output like PyModeller did
        # (after all we are just a reader) so don't specify any 
        # creation options. Not sure if this will cause problems...
        
        # input and output files
        cmdList.append(infile)
        cmdList.append(temp_image)
       
        # delete later - add before the system call as if Ctrl-C is hit 
        # control does not always return
        self.filestoremove.append(temp_image)
        self.filestoremove.append(src_prf)
        self.filestoremove.append(dest_prf)
          
        # run the command using subprocess
        # send any output to our self.loggingstream
        # - this is the main advantage over os.system()
        returncode = subprocess.call(cmdList,
                stdout=self.loggingstream,
                stderr=self.loggingstream)

        if returncode != 0:
            msg = 'Unable to run gdalwarp'
            raise rioserrors.GdalWarpNotFoundError(msg)
          
        # open the new temp file
        newds = gdal.Open(temp_image)
        if newds is None:
            msg = 'Unable to Open %s' % temp_image
            raise rioserrors.ImageOpenError(msg)
        
        # return the new dataset
        return newds
Пример #23
0
def _gdal_api_proxy_sub():

    src_ds = gdal.Open('data/byte.tif')
    src_cs = src_ds.GetRasterBand(1).Checksum()
    src_gt = src_ds.GetGeoTransform()
    src_prj = src_ds.GetProjectionRef()
    src_data = src_ds.ReadRaster(0, 0, 20, 20)
    src_md = src_ds.GetMetadata()
    src_ds = None

    drv = gdal.IdentifyDriver('data/byte.tif')
    assert drv.GetDescription() == 'API_PROXY'

    ds = gdal.GetDriverByName('GTiff').Create('tmp/byte.tif', 1, 1, 3)
    ds = None

    src_ds = gdal.Open('data/byte.tif')
    ds = gdal.GetDriverByName('GTiff').CreateCopy('tmp/byte.tif',
                                                  src_ds,
                                                  options=['TILED=YES'])
    got_cs = ds.GetRasterBand(1).Checksum()
    assert src_cs == got_cs
    ds = None

    ds = gdal.Open('tmp/byte.tif', gdal.GA_Update)

    ds.SetGeoTransform([1, 2, 3, 4, 5, 6])
    got_gt = ds.GetGeoTransform()
    assert src_gt != got_gt

    ds.SetGeoTransform(src_gt)
    got_gt = ds.GetGeoTransform()
    assert src_gt == got_gt

    assert ds.GetGCPCount() == 0

    assert ds.GetGCPProjection() == '', ds.GetGCPProjection()

    assert not ds.GetGCPs()

    gcps = [gdal.GCP(0, 1, 2, 3, 4)]
    sr = osr.SpatialReference()
    sr.ImportFromEPSG(4326)
    wkt = sr.ExportToWkt()
    assert ds.SetGCPs(gcps, wkt) == 0

    got_gcps = ds.GetGCPs()
    assert len(got_gcps) == 1

    assert (got_gcps[0].GCPLine == gcps[0].GCPLine and  \
       got_gcps[0].GCPPixel == gcps[0].GCPPixel and  \
       got_gcps[0].GCPX == gcps[0].GCPX and \
       got_gcps[0].GCPY == gcps[0].GCPY)

    assert ds.GetGCPProjection() == wkt

    ds.SetGCPs([], "")

    assert not ds.GetGCPs()

    ds.SetProjection('')
    got_prj = ds.GetProjectionRef()
    assert src_prj != got_prj

    ds.SetProjection(src_prj)
    got_prj = ds.GetProjectionRef()
    assert src_prj == got_prj

    ds.GetRasterBand(1).Fill(0)
    got_cs = ds.GetRasterBand(1).Checksum()
    assert got_cs == 0

    ds.GetRasterBand(1).WriteRaster(0, 0, 20, 20, src_data)
    got_cs = ds.GetRasterBand(1).Checksum()
    assert src_cs == got_cs

    ds.GetRasterBand(1).Fill(0)
    got_cs = ds.GetRasterBand(1).Checksum()
    assert got_cs == 0

    ds.WriteRaster(0, 0, 20, 20, src_data)
    got_cs = ds.GetRasterBand(1).Checksum()
    assert src_cs == got_cs

    # Not bound to SWIG
    # ds.AdviseRead(0,0,20,20,20,20)

    got_data = ds.ReadRaster(0, 0, 20, 20)
    assert src_data == got_data

    got_data = ds.GetRasterBand(1).ReadRaster(0, 0, 20, 20)
    assert src_data == got_data

    got_data_weird_spacing = ds.ReadRaster(0,
                                           0,
                                           20,
                                           20,
                                           buf_pixel_space=1,
                                           buf_line_space=32)
    assert len(got_data_weird_spacing) == 32 * (20 - 1) + 20

    assert got_data[20:20 + 20] == got_data_weird_spacing[32:32 + 20]

    got_data_weird_spacing = ds.GetRasterBand(1).ReadRaster(0,
                                                            0,
                                                            20,
                                                            20,
                                                            buf_pixel_space=1,
                                                            buf_line_space=32)
    assert len(got_data_weird_spacing) == 32 * (20 - 1) + 20

    assert got_data[20:20 + 20] == got_data_weird_spacing[32:32 + 20]

    got_block = ds.GetRasterBand(1).ReadBlock(0, 0)
    assert len(got_block) == 256 * 256

    assert got_data[20:20 + 20] == got_block[256:256 + 20]

    ds.FlushCache()
    ds.GetRasterBand(1).FlushCache()

    got_data = ds.GetRasterBand(1).ReadRaster(0, 0, 20, 20)
    assert src_data == got_data

    assert len(ds.GetFileList()) == 1

    assert ds.AddBand(gdal.GDT_Byte) != 0

    got_md = ds.GetMetadata()
    assert src_md == got_md

    assert ds.GetMetadataItem('AREA_OR_POINT') == 'Area'

    assert ds.GetMetadataItem('foo') is None

    ds.SetMetadataItem('foo', 'bar')
    assert ds.GetMetadataItem('foo') == 'bar'

    ds.SetMetadata({'foo': 'baz'}, 'OTHER')
    assert ds.GetMetadataItem('foo', 'OTHER') == 'baz'

    ds.GetRasterBand(1).SetMetadata({'foo': 'baw'}, 'OTHER')
    assert ds.GetRasterBand(1).GetMetadataItem('foo', 'OTHER') == 'baw'

    assert ds.GetMetadataItem('INTERLEAVE', 'IMAGE_STRUCTURE') == 'BAND'

    assert not ds.GetRasterBand(1).GetMetadata()

    assert ds.GetRasterBand(1).GetMetadataItem('foo') is None

    ds.GetRasterBand(1).SetMetadataItem('foo', 'baz')
    assert ds.GetRasterBand(1).GetMetadataItem('foo') == 'baz'

    ds.GetRasterBand(1).SetMetadata({'foo': 'baw'})
    assert ds.GetRasterBand(1).GetMetadataItem('foo') == 'baw'

    assert ds.GetRasterBand(1).GetColorInterpretation() == gdal.GCI_GrayIndex

    ds.GetRasterBand(1).SetColorInterpretation(gdal.GCI_Undefined)

    ct = ds.GetRasterBand(1).GetColorTable()
    assert ct is None

    ct = gdal.ColorTable()
    ct.SetColorEntry(0, (1, 2, 3))
    assert ds.GetRasterBand(1).SetColorTable(ct) == 0

    ct = ds.GetRasterBand(1).GetColorTable()
    assert ct is not None
    assert ct.GetColorEntry(0) == (1, 2, 3, 255)

    ct = ds.GetRasterBand(1).GetColorTable()
    assert ct is not None

    assert ds.GetRasterBand(1).SetColorTable(None) == 0

    ct = ds.GetRasterBand(1).GetColorTable()
    assert ct is None

    rat = ds.GetRasterBand(1).GetDefaultRAT()
    assert rat is None

    assert ds.GetRasterBand(1).SetDefaultRAT(None) == 0

    ref_rat = gdal.RasterAttributeTable()
    assert ds.GetRasterBand(1).SetDefaultRAT(ref_rat) == 0

    rat = ds.GetRasterBand(1).GetDefaultRAT()
    assert rat is None

    assert ds.GetRasterBand(1).SetDefaultRAT(None) == 0

    rat = ds.GetRasterBand(1).GetDefaultRAT()
    assert rat is None

    assert ds.GetRasterBand(1).GetMinimum() is None

    got_stats = ds.GetRasterBand(1).GetStatistics(0, 0)
    assert got_stats[3] < 0.0

    got_stats = ds.GetRasterBand(1).GetStatistics(1, 1)
    assert got_stats[0] == 74.0

    assert ds.GetRasterBand(1).GetMinimum() == 74.0

    assert ds.GetRasterBand(1).GetMaximum() == 255.0

    ds.GetRasterBand(1).SetStatistics(1, 2, 3, 4)
    got_stats = ds.GetRasterBand(1).GetStatistics(1, 1)
    assert got_stats == [1, 2, 3, 4]

    ds.GetRasterBand(1).ComputeStatistics(0)
    got_stats = ds.GetRasterBand(1).GetStatistics(1, 1)
    assert got_stats[0] == 74.0

    minmax = ds.GetRasterBand(1).ComputeRasterMinMax()
    assert minmax == (74.0, 255.0)

    assert ds.GetRasterBand(1).GetOffset() == 0.0

    assert ds.GetRasterBand(1).GetScale() == 1.0

    ds.GetRasterBand(1).SetOffset(10.0)
    assert ds.GetRasterBand(1).GetOffset() == 10.0

    ds.GetRasterBand(1).SetScale(2.0)
    assert ds.GetRasterBand(1).GetScale() == 2.0

    ds.BuildOverviews('NEAR', [2])
    assert ds.GetRasterBand(1).GetOverviewCount() == 1

    assert ds.GetRasterBand(1).GetOverview(-1) is None

    assert ds.GetRasterBand(1).GetOverview(0) is not None

    assert ds.GetRasterBand(1).GetOverview(0) is not None

    got_hist = ds.GetRasterBand(1).GetHistogram()
    assert len(got_hist) == 256

    (minval, maxval, nitems,
     got_hist2) = ds.GetRasterBand(1).GetDefaultHistogram()
    assert minval == -0.5
    assert maxval == 255.5
    assert nitems == 256
    assert got_hist == got_hist2

    ds.GetRasterBand(1).SetDefaultHistogram(1, 2, [3])
    (minval, maxval, nitems,
     got_hist3) = ds.GetRasterBand(1).GetDefaultHistogram()
    assert minval == 1
    assert maxval == 2
    assert nitems == 1
    assert got_hist3[0] == 3

    got_nodatavalue = ds.GetRasterBand(1).GetNoDataValue()
    assert got_nodatavalue is None

    ds.GetRasterBand(1).SetNoDataValue(123)
    got_nodatavalue = ds.GetRasterBand(1).GetNoDataValue()
    assert got_nodatavalue == 123

    assert ds.GetRasterBand(1).GetMaskFlags() == 8

    assert ds.GetRasterBand(1).GetMaskBand() is not None

    ret = ds.GetRasterBand(1).DeleteNoDataValue()
    assert ret == 0
    got_nodatavalue = ds.GetRasterBand(1).GetNoDataValue()
    assert got_nodatavalue is None

    ds.CreateMaskBand(0)

    assert ds.GetRasterBand(1).GetMaskFlags() == 2

    assert ds.GetRasterBand(1).GetMaskBand() is not None

    ds.GetRasterBand(1).CreateMaskBand(0)

    assert ds.GetRasterBand(1).HasArbitraryOverviews() == 0

    ds.GetRasterBand(1).SetUnitType('foo')
    assert ds.GetRasterBand(1).GetUnitType() == 'foo'

    assert ds.GetRasterBand(1).GetCategoryNames() is None

    ds.GetRasterBand(1).SetCategoryNames(['foo'])
    assert ds.GetRasterBand(1).GetCategoryNames() == ['foo']

    ds.GetRasterBand(1).SetDescription('bar')

    ds = None

    gdal.GetDriverByName('GTiff').Delete('tmp/byte.tif')
Пример #24
0
    def resampleToReference(self,
                            ds,
                            nullValList,
                            workingRegion,
                            resamplemethod,
                            tempdir='.',
                            useVRT=False,
                            allowOverviewsGdalwarp=False):
        """
        Resamples any inputs that do not match the reference, to the 
        reference image. 
        
        ds is the GDAL dataset that needs to be resampled.
        nullValList is the list of null values for that dataset.
        workingRegion is a PixelGridDefn
        resamplemethod is a string containing a method supported by gdalwarp.
        
        Returns the new (temporary) resampled dataset instance.
        
        Do not call directly, use resampleAllToReference()
        
        """

        # get the name of the input file
        infile = ds.GetDescription()

        # create temporary .prf files with the source
        # and destination WKT strings.
        import tempfile
        # the src prf file
        (fileh, src_prf) = tempfile.mkstemp('.prf', dir=tempdir)
        fileobj = os.fdopen(fileh, 'w')
        srcproj = self.specialProjFixes(ds.GetProjection())
        fileobj.write(srcproj)
        fileobj.close()

        # the dest prf file
        (fileh, dest_prf) = tempfile.mkstemp('.prf', dir=tempdir)
        fileobj = os.fdopen(fileh, 'w')
        fileobj.write(self.referencePixGrid.projection)
        fileobj.close()

        if useVRT:
            ext = '.vrt'
        else:
            # get the driver from the input dataset
            # so we know the default extension, and type
            # for the temporary file.
            driver = gdal.IdentifyDriver(infile)
            drivermeta = driver.GetMetadata()

            # temp image file name - based on driver extension
            ext = ''
            if gdal.DMD_EXTENSION in drivermeta:
                ext = '.' + drivermeta[gdal.DMD_EXTENSION]

        (fileh, temp_image) = tempfile.mkstemp(ext, dir=tempdir)
        os.close(fileh)

        # see if gdalwarp actually exists on the system so we can
        # provide a separate error if we can't find it vs there was an error
        # running it.
        gdalwarp_path = find_executable(GDALWARP)
        if gdalwarp_path is None:
            msg = 'Unable to find %s executable on the system' % GDALWARP
            raise rioserrors.GdalWarpNotFoundError(msg)

        # build the command line for gdalwarp
        # as a list for subprocess - also a bit easier to read
        cmdList = [gdalwarp_path]

        if LooseVersion(gdal.__version__) >= LooseVersion('2.0'):
            if not allowOverviewsGdalwarp:
                cmdList.extend(['-ovr', 'NONE'])

        # source projection prf file
        cmdList.append('-s_srs')
        cmdList.append(src_prf)

        # destination projection prf file
        cmdList.append('-t_srs')
        cmdList.append(dest_prf)

        # extent. Note the use of repr() to avoid loss of precision.
        cmdList.append('-te')
        for x in [
                workingRegion.xMin, workingRegion.yMin, workingRegion.xMax,
                workingRegion.yMax
        ]:
            cmdList.append(repr(x))

        # resolution. Note the use of repr() to avoid loss of precision.
        cmdList.append('-tr')
        for x in [workingRegion.xRes, workingRegion.yRes]:
            cmdList.append(repr(x))

        # output format
        cmdList.append('-of')
        if useVRT:
            driverName = 'VRT'
        else:
            driverName = driver.ShortName
        cmdList.append(driverName)

        # resample method
        cmdList.append('-r')
        cmdList.append(resamplemethod)

        # null values
        nullOptions = self.makeWarpNullOptions(nullValList)
        if nullOptions is not None:
            cmdList.extend(nullOptions)

        # don't have creation options for output like PyModeller did
        # (after all we are just a reader) so don't specify any
        # creation options. Not sure if this will cause problems...

        # input and output files
        cmdList.append(infile)
        cmdList.append(temp_image)

        # delete later - add before the system call as if Ctrl-C is hit
        # control does not always return
        self.filestoremove.append(temp_image)
        self.filestoremove.append(src_prf)
        self.filestoremove.append(dest_prf)

        # run the command using subprocess
        # send any output to our self.loggingstream
        # - this is the main advantage over os.system()
        returncode = subprocess.call(cmdList,
                                     stdout=self.loggingstream,
                                     stderr=self.loggingstream)

        if returncode != 0:
            if returncode < 0:
                # From the subprocess.call help:
                # A negative value -N indicates that the child was
                # terminated by signal N (POSIX only).
                msg = ("%s was terminated by signal %d. Try setting the " +
                       "RIOS_NO_VRT_FOR_RESAMPLING environment variable " +
                       "to '1'") % (GDALWARP, abs(returncode))
                raise rioserrors.GdalWarpError(msg)
            else:
                msg = ("Error while running %s. Try setting the " +
                       "RIOS_NO_VRT_FOR_RESAMPLING environment variable " +
                       "to '1'") % GDALWARP
                raise rioserrors.GdalWarpError(msg)

        # open the new temp file
        newds = gdal.Open(temp_image)
        if newds is None:
            msg = 'Unable to Open %s' % temp_image
            raise rioserrors.ImageOpenError(msg)

        # return the new dataset
        return newds