def main(argv=sys.argv): scope = SCOPES['ft'] token_in = None command = None argv = gdal.GeneralCmdLineProcessor(sys.argv) if argv is None: return 0 # Parse command line arguments. i = 1 while i < len(argv): arg = argv[i] if arg == '-s' and i < len(argv) - 1: if argv[i + 1] in SCOPES: scope = SCOPES[argv[i + 1]] elif argv[i + 1].startswith('http'): scope = argv[i + 1] else: print('Scope %s not recognised.' % argv[i + 1]) return Usage() i = i + 1 elif arg[0] == '-': return Usage() elif command is None: command = arg elif token_in is None: token_in = arg else: return Usage() i = i + 1 if command is None: command = 'interactive' if command == 'login': print(gdal.GOA2GetAuthorizationURL(scope)) elif command == 'auth2refresh': print(gdal.GOA2GetRefreshToken(token_in, scope)) elif command == 'refresh2access': print(gdal.GOA2GetAccessToken(token_in, scope)) elif command != 'interactive': return Usage() else: # Interactive case print('Authorization requested for scope:') print(scope) print('') print('Please login and authorize access in web browser...') webbrowser.open(gdal.GOA2GetAuthorizationURL(scope)) time.sleep(2.0) print('') print('Enter authorization token:') auth_token = sys.stdin.readline() refresh_token = gdal.GOA2GetRefreshToken(auth_token, scope) print('Refresh Token:' + refresh_token) print('') if scope == SCOPES['ft']: print('Consider setting a configuration option like:') print('GFT_REFRESH_TOKEN=' + refresh_token) elif scope in (SCOPES['storage'], SCOPES['storage-rw']): print('Consider setting a configuration option like:') print('GS_OAUTH2_REFRESH_TOKEN=' + refresh_token)
def gdal_edit(argv): argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return -1 datasetname = None srs = None ulx = None uly = None lrx = None lry = None nodata = None xres = None yres = None unsetgt = False unsetstats = False stats = False approx_stats = False unsetmd = False ro = False molist = [] gcp_list = [] open_options = [] i = 1 argc = len(argv) while i < argc: if argv[i] == '-ro': ro = True elif argv[i] == '-a_srs' and i < len(argv) - 1: srs = argv[i + 1] i = i + 1 elif argv[i] == '-a_ullr' and i < len(argv) - 4: ulx = float(argv[i + 1]) i = i + 1 uly = float(argv[i + 1]) i = i + 1 lrx = float(argv[i + 1]) i = i + 1 lry = float(argv[i + 1]) i = i + 1 elif argv[i] == '-tr' and i < len(argv) - 2: xres = float(argv[i + 1]) i = i + 1 yres = float(argv[i + 1]) i = i + 1 elif argv[i] == '-a_nodata' and i < len(argv) - 1: nodata = float(argv[i + 1]) i = i + 1 elif argv[i] == '-mo' and i < len(argv) - 1: molist.append(argv[i + 1]) i = i + 1 elif argv[i] == '-gcp' and i + 4 < len(argv): pixel = float(argv[i + 1]) i = i + 1 line = float(argv[i + 1]) i = i + 1 x = float(argv[i + 1]) i = i + 1 y = float(argv[i + 1]) i = i + 1 if i + 1 < len(argv) and ArgIsNumeric(argv[i + 1]): z = float(argv[i + 1]) i = i + 1 else: z = 0 gcp = gdal.GCP(x, y, z, pixel, line) gcp_list.append(gcp) elif argv[i] == '-unsetgt': unsetgt = True elif argv[i] == '-unsetstats': unsetstats = True elif argv[i] == '-approx_stats': stats = True approx_stats = True elif argv[i] == '-stats': stats = True elif argv[i] == '-unsetmd': unsetmd = True elif argv[i] == '-oo' and i < len(argv) - 1: open_options.append(argv[i + 1]) i = i + 1 elif argv[i][0] == '-': sys.stderr.write('Unrecognized option : %s\n' % argv[i]) return Usage() elif datasetname is None: datasetname = argv[i] else: sys.stderr.write('Unexpected option : %s\n' % argv[i]) return Usage() i = i + 1 if datasetname is None: return Usage() if (srs is None and lry is None and yres is None and not unsetgt and not unsetstats and not stats and nodata is None and len(molist) == 0 and not unsetmd): print('No option specified') print('') return Usage() exclusive_option = 0 if lry is not None: exclusive_option = exclusive_option + 1 if yres is not None: exclusive_option = exclusive_option + 1 if unsetgt: exclusive_option = exclusive_option + 1 if exclusive_option > 1: print('-a_ullr, -tr and -unsetgt options are exclusive.') print('') return Usage() if unsetstats and stats: print( '-unsetstats and either -stats or -approx_stats options are exclusive.' ) print('') return Usage() if open_options is not None: if ro: ds = gdal.OpenEx(datasetname, gdal.OF_RASTER, open_options=open_options) else: ds = gdal.OpenEx(datasetname, gdal.OF_RASTER | gdal.OF_UPDATE, open_options=open_options) # GDAL 1.X compat elif ro: ds = gdal.Open(datasetname) else: ds = gdal.Open(datasetname, gdal.GA_Update) if ds is None: return -1 wkt = None if srs == '' or srs == 'None': ds.SetProjection('') elif srs is not None: sr = osr.SpatialReference() if sr.SetFromUserInput(srs) != 0: print('Failed to process SRS definition: %s' % srs) return -1 wkt = sr.ExportToWkt() if len(gcp_list) == 0: ds.SetProjection(wkt) if lry is not None: gt = [ ulx, (lrx - ulx) / ds.RasterXSize, 0, uly, 0, (lry - uly) / ds.RasterYSize ] ds.SetGeoTransform(gt) if yres is not None: gt = ds.GetGeoTransform() # Doh ! why is gt a tuple and not an array... gt = [gt[j] for j in range(6)] gt[1] = xres gt[5] = yres ds.SetGeoTransform(gt) if unsetgt: ds.SetGeoTransform([0, 1, 0, 0, 0, 1]) if len(gcp_list) > 0: if wkt is None: wkt = ds.GetGCPProjection() if wkt is None: wkt = '' ds.SetGCPs(gcp_list, wkt) if nodata is not None: for i in range(ds.RasterCount): ds.GetRasterBand(i + 1).SetNoDataValue(nodata) if unsetstats: for i in range(ds.RasterCount): band = ds.GetRasterBand(i + 1) for key in band.GetMetadata().keys(): if key.startswith('STATISTICS_'): band.SetMetadataItem(key, None) if stats: for i in range(ds.RasterCount): ds.GetRasterBand(i + 1).ComputeStatistics(approx_stats) if len(molist) != 0: if unsetmd: md = {} else: md = ds.GetMetadata() for moitem in molist: equal_pos = moitem.find('=') if equal_pos > 0: md[moitem[0:equal_pos]] = moitem[equal_pos + 1:] ds.SetMetadata(md) elif unsetmd: ds.SetMetadata({}) ds = band = None return 0
def gdal_ls(argv, fout=sys.stdout): longformat = False recurse = False recurseInZip = False recurseInTGZ = False display_prefix = True dirname = None depth = 1024 argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return -1 i = 1 argc = len(argv) while i < argc: if argv[i] == '-l': longformat = True elif argv[i] == '-lr': longformat = True recurse = True elif argv[i] == '-R' or argv[i] == '-r': recurse = True elif argv[i] == '-Rzip': recurseInZip = True elif argv[i] == '-Rtgz': recurseInTGZ = True elif argv[i] == '-noprefix': display_prefix = False elif argv[i] == '-depth' and i < len(argv) - 1: depth = int(argv[i + 1]) i = i + 1 elif argv[i][0] == '-': sys.stderr.write('Unrecognized option : %s\n' % argv[i]) return Usage() elif dirname is None: dirname = argv[i] else: sys.stderr.write('Unexpected option : %s\n' % argv[i]) return Usage() i = i + 1 if dirname is None: return Usage() # Remove trailing if dirname[-1] == '/': dirname = dirname[0:len(dirname) - 1] if needsVSICurl(dirname): dirname = '/vsicurl/' + dirname # if iszip(dirname) and not dirname.startswith('/vsizip'): # dirname = '/vsizip/' + dirname # if istgz(dirname) and not dirname.startswith('/vsitar'): # dirname = '/vsitar/' + dirname prefix = '' if display_prefix: prefix = dirname + '/' readDir(fout, dirname, prefix, longformat, recurse, depth, recurseInZip, recurseInTGZ, True) return 0
def main(argv=sys.argv): argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 0 driver_name = 'GTiff' src_color_filename = None src_greyscale_filename = None dst_color_filename = None quiet = False # Parse command line arguments. i = 1 while i < len(argv): arg = argv[i] if arg == '-of': i = i + 1 driver_name = argv[i] elif arg == '-q' or arg == '-quiet': quiet = True elif src_color_filename is None: src_color_filename = argv[i] elif src_greyscale_filename is None: src_greyscale_filename = argv[i] elif dst_color_filename is None: dst_color_filename = argv[i] else: return Usage() i = i + 1 if dst_color_filename is None: return Usage() datatype = gdal.GDT_Byte hilldataset = gdal.Open(src_greyscale_filename, gdal.GA_ReadOnly) colordataset = gdal.Open(src_color_filename, gdal.GA_ReadOnly) # check for 3 or 4 bands in the color file if (colordataset.RasterCount != 3 and colordataset.RasterCount != 4): print( 'Source image does not appear to have three or four bands as required.' ) return 1 # define output format, name, size, type and set projection out_driver = gdal.GetDriverByName(driver_name) outdataset = out_driver.Create(dst_color_filename, colordataset.RasterXSize, colordataset.RasterYSize, colordataset.RasterCount, datatype) outdataset.SetProjection(hilldataset.GetProjection()) outdataset.SetGeoTransform(hilldataset.GetGeoTransform()) # assign RGB and hillshade bands rBand = colordataset.GetRasterBand(1) gBand = colordataset.GetRasterBand(2) bBand = colordataset.GetRasterBand(3) if colordataset.RasterCount == 4: aBand = colordataset.GetRasterBand(4) else: aBand = None hillband = hilldataset.GetRasterBand(1) hillbandnodatavalue = hillband.GetNoDataValue() # check for same file size if ((rBand.YSize != hillband.YSize) or (rBand.XSize != hillband.XSize)): print('Color and hillshade must be the same size in pixels.') return 1 # loop over lines to apply hillshade for i in range(hillband.YSize): # load RGB and Hillshade arrays rScanline = rBand.ReadAsArray(0, i, hillband.XSize, 1, hillband.XSize, 1) gScanline = gBand.ReadAsArray(0, i, hillband.XSize, 1, hillband.XSize, 1) bScanline = bBand.ReadAsArray(0, i, hillband.XSize, 1, hillband.XSize, 1) hillScanline = hillband.ReadAsArray(0, i, hillband.XSize, 1, hillband.XSize, 1) # convert to HSV hsv = rgb_to_hsv(rScanline, gScanline, bScanline) # if there's nodata on the hillband, use the v value from the color # dataset instead of the hillshade value. if hillbandnodatavalue is not None: equal_to_nodata = numpy.equal(hillScanline, hillbandnodatavalue) v = numpy.choose(equal_to_nodata, (hillScanline, hsv[2])) else: v = hillScanline # replace v with hillshade hsv_adjusted = numpy.asarray([hsv[0], hsv[1], v]) # convert back to RGB dst_color = hsv_to_rgb(hsv_adjusted) # write out new RGB bands to output one band at a time outband = outdataset.GetRasterBand(1) outband.WriteArray(dst_color[0], 0, i) outband = outdataset.GetRasterBand(2) outband.WriteArray(dst_color[1], 0, i) outband = outdataset.GetRasterBand(3) outband.WriteArray(dst_color[2], 0, i) if aBand is not None: aScanline = aBand.ReadAsArray(0, i, hillband.XSize, 1, hillband.XSize, 1) outband = outdataset.GetRasterBand(4) outband.WriteArray(aScanline, 0, i) # update progress line if not quiet: gdal.TermProgress_nocb((float(i + 1) / hillband.YSize)) return 0
def main(argv=sys.argv): ntv2_filename = None loslas_list = [] auto_flag = 0 options = Options() argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 0 # Parse command line arguments. i = 1 while i < len(argv): arg = argv[i] if arg == '-v': options.verbose_flag = 1 elif arg == '-version' and i < len(argv) - 1: options.metadata.append('VERSION=' + argv[i + 1]) i = i + 1 elif arg == '-created' and i < len(argv) - 1: options.metadata.append('CREATED=' + argv[i + 1]) i = i + 1 elif arg == '-updated' and i < len(argv) - 1: options.metadata.append('UPDATED=' + argv[i + 1]) i = i + 1 elif arg == '-system_f' and i < len(argv) - 1: options.metadata.append('SYSTEM_F=' + argv[i + 1]) i = i + 1 elif arg == '-system_t' and i < len(argv) - 1: options.metadata.append('SYSTEM_T=' + argv[i + 1]) i = i + 1 elif arg == '-parent' and i < len(argv) - 1: options.metadata.append('PARENT=' + argv[i + 1]) i = i + 1 elif arg == '-sub_name' and i < len(argv) - 1: options.metadata.append('SUB_NAME=' + argv[i + 1]) i = i + 1 elif arg == '-gs_type' and i < len(argv) - 1: options.metadata.append('GS_TYPE=' + argv[i + 1]) i = i + 1 elif arg == '-major_f' and i < len(argv) - 1: options.metadata.append('MAJOR_F=' + argv[i + 1]) i = i + 1 elif arg == '-minor_f' and i < len(argv) - 1: options.metadata.append('MINOR_F=' + argv[i + 1]) i = i + 1 elif arg == '-major_t' and i < len(argv) - 1: options.metadata.append('MAJOR_T=' + argv[i + 1]) i = i + 1 elif arg == '-minor_t' and i < len(argv) - 1: options.metadata.append('MINOR_T=' + argv[i + 1]) i = i + 1 elif arg == '-negate': options.negate = 1 elif arg == '-auto': auto_flag = 1 elif arg == '-a': options.append = 1 elif arg[0] == '-': return Usage() elif arg[-4:] == '.los' or arg[-4:] == '.las': loslas_list.append(arg) elif arg[-4:] == '.gsb' and ntv2_filename is None: ntv2_filename = arg else: print('Unrecognized argument: ', arg) return Usage() i = i + 1 if not loslas_list: print('No .los/.las files specified as input.') return Usage() if auto_flag == 1: auto_noaa(options, loslas_list) if ntv2_filename is None: print('No NTv2 file specified.') return Usage() # Process loslas files. for los in loslas_list: TranslateLOSLAS(los, ntv2_filename, options) options.append = 1 return 0
def gdal_cp(argv, progress=None): srcfile = None targetfile = None recurse = False skip_failure = False argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return -1 for i in range(1, len(argv)): if argv[i] == '-progress': progress = TermProgress() elif argv[i] == '-r': version_num = int(gdal.VersionInfo('VERSION_NUM')) if version_num < 1900: print( 'ERROR: Python bindings of GDAL 1.9.0 or later required for -r option' ) return -1 recurse = True elif len(argv[i]) >= 5 and argv[i][0:5] == '-skip': skip_failure = True elif argv[i][0] == '-': print('Unrecognized option : %s' % argv[i]) return Usage() elif srcfile is None: srcfile = argv[i] elif targetfile is None: targetfile = argv[i] else: print('Unexpected option : %s' % argv[i]) return Usage() if srcfile is None or targetfile is None: return Usage() if needsVSICurl(srcfile): srcfile = '/vsicurl/' + srcfile if recurse: # Make sure that 'gdal_cp.py -r [srcdir/]lastsubdir targetdir' creates # targetdir/lastsubdir if targetdir already exists (like cp -r does). if srcfile[-1] == '/': srcfile = srcfile[0:len(srcfile) - 1] statBufSrc = gdal.VSIStatL( srcfile, gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG) if statBufSrc is None: statBufSrc = gdal.VSIStatL( srcfile + '/', gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG) statBufDst = gdal.VSIStatL( targetfile, gdal.VSI_STAT_EXISTS_FLAG | gdal.VSI_STAT_NATURE_FLAG) if statBufSrc is not None and statBufSrc.IsDirectory( ) and statBufDst is not None and statBufDst.IsDirectory(): if targetfile[-1] == '/': targetfile = targetfile[0:-1] if srcfile.rfind('/') != -1: targetfile = targetfile + srcfile[srcfile.rfind('/'):] else: targetfile = targetfile + '/' + srcfile if gdal.VSIStatL(targetfile) is None: gdal.Mkdir(targetfile, int('0755', 8)) return gdal_cp_recurse(srcfile, targetfile, progress, skip_failure) (srcdir, pattern) = os.path.split(srcfile) if pattern.find('*') != -1 or pattern.find('?') != -1: return gdal_cp_pattern_match(srcdir, pattern, targetfile, progress, skip_failure) else: return gdal_cp_single(srcfile, targetfile, progress)
def gdal_edit(argv): argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return -1 datasetname = None maskname = None outputname = None srs = None ulx = None uly = None lrx = None lry = None nodata = None xres = None yres = None unsetgt = False molist = [] i = 1 argc = len(argv) while i < argc: if argv[i] == '-a_srs' and i < len(argv) - 1: srs = argv[i + 1] i = i + 1 elif argv[i] == '-a_ullr' and i < len(argv) - 4: ulx = float(argv[i + 1]) i = i + 1 uly = float(argv[i + 1]) i = i + 1 lrx = float(argv[i + 1]) i = i + 1 lry = float(argv[i + 1]) i = i + 1 elif argv[i] == '-tr' and i < len(argv) - 2: xres = float(argv[i + 1]) i = i + 1 yres = float(argv[i + 1]) i = i + 1 elif argv[i] == '-a_nodata' and i < len(argv) - 1: nodata = float(argv[i + 1]) i = i + 1 elif argv[i] == '-mo' and i < len(argv) - 1: molist.append(argv[i + 1]) i = i + 1 elif argv[i] == '-unsetgt': unsetgt = True elif argv[i][0] == '-': sys.stderr.write('Unrecognized option : %s\n' % argv[i]) return Usage() elif datasetname is None: datasetname = argv[i] elif maskname is None: maskname = argv[i] elif outputname is None: outputname = argv[i] else: sys.stderr.write('Unexpected option : %s\n' % argv[i]) return Usage() i = i + 1 if datasetname is None: return Usage() if maskname is None: return Usage() if outputname is None: return Usage() if srs is None and lry is None and yres is None and not unsetgt and nodata is None and len( molist) == 0: print('No option specified') print('') return Usage() exclusive_option = 0 if lry is not None: exclusive_option = exclusive_option + 1 if yres is not None: exclusive_option = exclusive_option + 1 if unsetgt: exclusive_option = exclusive_option + 1 if exclusive_option > 1: print('-a_ullr, -tr and -unsetgt options are exclusive.') print('') return Usage() source = gdal.Open(datasetname, gdal.GA_ReadOnly) alphaBand = gdal.Open(maskname, gdal.GA_ReadOnly) bands = [source.GetRasterBand(i + 1) for i in range(source.RasterCount)] # check that bands 1-3 are RGB #assert [band.GetColorInterpretation() for band in bands] == [gdal.GCI_RedBand, gdal.GCI_GreenBand, gdal.GCI_BlueBand] target = gdal.GetDriverByName('GTiff').Create( outputname, source.RasterXSize, source.RasterYSize, 3, gdal.GDT_Byte, ['PHOTOMETRIC=YCBCR', 'COMPRESS=JPEG', 'TILED=YES']) if target is None: return -1 # copy georef target.SetProjection(source.GetProjection()) target.SetGeoTransform(source.GetGeoTransform()) if srs is not None: srs_real = osr.SpatialReference() srs_real.ImportFromProj4(srs) target.SetProjection(srs_real.ExportToWkt()) if lry is not None: gt = [ ulx, (lrx - ulx) / target.RasterXSize, 0, uly, 0, (lry - uly) / target.RasterYSize ] target.SetGeoTransform(gt) if yres is not None: gt = target.GetGeoTransform() # Doh ! why is gt a tuple and not an array... gt = [gt[i] for i in range(6)] gt[1] = xres gt[5] = yres target.SetGeoTransform(gt) if unsetgt: target.SetGeoTransform([0, 1, 0, 0, 0, 1]) if nodata is not None: for i in range(target.RasterCount): target.GetRasterBand(1).SetNoDataValue(nodata) if len(molist) != 0: target.SetMetadata(molist) target_bands = [target.GetRasterBand(i + 1) for i in range(3)] block_width, block_height = target_bands[0].GetBlockSize() # Use straight up black if neither alpha nor nodata is present nodata = [band.GetNoDataValue() for band in bands] use_alpha = True #(len(bands) > 4) use_nodata = False #(not use_alpha and len([n for n in nodata if n is not None]) == 3) print >> sys.stderr, "Generating mask from", if use_alpha: print >> sys.stderr, "alpha band." else: if use_nodata: print >> sys.stderr, "NODATA values." nodata = [chr(int(n)) for n in nodata] else: print >> sys.stderr, "black pixels." nodata = ["\0", "\0", "\0"] use_nodata = True target.CreateMaskBand(gdal.GMF_PER_DATASET) mask_band = target_bands[0].GetMaskBand() total_blocks = (target.RasterXSize * target.RasterYSize) / float( block_width * block_height) blocks_written = 0 sys.stderr.write("0...") for col in range(0, target.RasterXSize, block_width): for row in range(0, target.RasterYSize, block_height): width = min(target.RasterXSize - col, block_width) height = min(target.RasterYSize - row, block_height) data = [ band.ReadRaster(col, row, width, height) for band in bands[:3] ] mask = array.array("B", (1 for x in range(len(data[0])))) alpha = alphaBand.ReadRaster(col, row, width, height) tuple = struct.unpack('B' * width * height, alpha) alpha = None if use_alpha: alpha = alphaBand.ReadRaster(col, row, width, height) # print len(alpha) # print tuple for byte in range(len(data[0])): if use_alpha: if not tuple[byte]: mask[byte] = 0 else: if data[0][byte] == nodata[0] and data[1][byte] == nodata[ 1] and data[2][byte] == nodata[2]: mask[byte] = 0 for n, block in enumerate(data): target_bands[n].WriteRaster(col, row, width, height, block) #print mask.tostring() mask_band.WriteRaster(col, row, width, height, mask.tostring()) if int(blocks_written / total_blocks * 10) != int( (blocks_written + 1) / total_blocks * 10): count = int((blocks_written + 1) / total_blocks * 10) sys.stderr.write("done." if count == 10 else "%d0..." % count) blocks_written += 1 sys.stderr.write("\n") mask_band = None target_bands = None target = None alphaBand = None
def main(argv=None): bReportHistograms = False bApproxStats = False scale = 1.0 offset = 0.0 bComputeMinMax = False bStats = False bScale = False pszFilename = None if argv is None: argv = sys.argv argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 1 nArgc = len(argv) #/* -------------------------------------------------------------------- */ #/* Parse arguments. */ #/* -------------------------------------------------------------------- */ i = 1 while i < nArgc: if EQUAL(argv[i], "--utility_version"): print(("%s is running against GDAL %s" % (argv[0], gdal.VersionInfo("RELEASE_NAME")))) return 0 elif EQUAL(argv[i], "-mm"): bComputeMinMax = True elif EQUAL(argv[i], "-unscale"): bScale = True elif EQUAL(argv[i], "-stats"): bStats = True elif EQUAL(argv[i], "-hist"): bReportHistograms = True elif argv[i][0] == '-': return Usage() elif pszFilename is None: pszFilename = argv[i] else: return Usage() i = i + 1 if pszFilename is None: return Usage() if not (bComputeMinMax or bScale or bStats or bReportHistograms): return Usage() #/* -------------------------------------------------------------------- */ #/* Open dataset. */ #/* -------------------------------------------------------------------- */ hDataset = gdal.Open(pszFilename, gdal.GA_ReadOnly) if hDataset is None: print(("gdalinfo failed - unable to open '%s'." % pszFilename)) return 1 #/* ==================================================================== */ #/* Loop over bands. */ #/* ==================================================================== */ for iBand in range(hDataset.RasterCount): hBand = hDataset.GetRasterBand(iBand + 1) (nBlockXSize, nBlockYSize) = hBand.GetBlockSize() if bScale: offset = hBand.GetOffset() if offset is None: offset = 0.0 scale = hBand.GetScale() if scale is None: scale = 1.0 if (hDataset.RasterCount > 1): print(( "Band %d Block=%dx%d Type=%s, ColorInterp=%s" % ( iBand+1, \ nBlockXSize, nBlockYSize, \ gdal.GetDataTypeName(hBand.DataType), \ gdal.GetColorInterpretationName( \ hBand.GetRasterColorInterpretation()) ))) dfMin = hBand.GetMinimum() dfMax = hBand.GetMaximum() if dfMin is not None or dfMax is not None or bComputeMinMax: line = "" if dfMin is not None: dfMin = (dfMin * scale) + offset line = line + ("Min=%.3f " % (dfMin)) if dfMax is not None: dfMax = (dfMax * scale) + offset line = line + ("Max=%.3f " % (dfMax)) if bComputeMinMax: gdal.ErrorReset() adfCMinMax = hBand.ComputeRasterMinMax(True) if gdal.GetLastErrorType() == gdal.CE_None: line = line + ( " Computed Min/Max=%.3f,%.3f" % ( \ ((adfCMinMax[0] * scale) + offset), \ ((adfCMinMax[1] * scale) + offset) )) print(line) #if bStats: # print( line ) stats = hBand.GetStatistics(bApproxStats, bStats) #inType = gdal.GetDataTypeName(hBand.DataType) # Dirty hack to recognize if stats are valid. If invalid, the returned # stddev is negative if stats[3] >= 0.0: if bStats: mean = (stats[2] * scale) + offset stdev = (stats[3] * scale) + offset rms = math.sqrt((mean * mean) + (stdev * stdev)) print(( "Min=%.2f, Max=%.2f, Mean=%.2f, StdDev=%.2f, RMS=%.2f" \ % ((stats[0] * scale) + offset, (stats[1] * scale) + offset,\ mean, stdev, rms ))) if bReportHistograms: print("level\tvalue\tcount\tcumulative") #Histogram call not returning exact min and max. #...Workaround run gdalinfo -stats and then use min/max from above hist = hBand.GetDefaultHistogram(force=True) #hist = hBand.GetDefaultHistogram(force = True, callback = gdal.TermProgress) cnt = 0 sum = 0 sumTotal = 0 if hist is not None: #use dfMin and dfMax from previous calls when possible if dfMin is None: dfMin = (hist[0] * scale) + offset if dfMax is None: dfMax = (hist[1] * scale) + offset nBucketCount = hist[2] panHistogram = hist[3] #print( " %d buckets from %g to %g:" % ( \ # nBucketCount, dfMin, dfMax )) #print ( "scale: %g, offset: %g" % (scale, offset)) increment = round(((dfMax - dfMin) / nBucketCount), 2) value = dfMin #get total to normalize (below) for bucket in panHistogram: sumTotal = sumTotal + bucket for bucket in panHistogram: sum = sum + bucket #normalize cumulative nsum = sum / float(sumTotal) line = "%d\t%0.2f\t%d\t%0.6f" % (cnt, value, bucket, nsum) print(line) cnt = cnt + 1 value = value + increment return True
def gdal_edit(argv): argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return -1 datasetname = None srs = None ulx = None uly = None lrx = None lry = None nodata = None xres = None yres = None unsetgt = False ro = False molist = [] gcp_list = [] i = 1 argc = len(argv) while i < argc: if argv[i] == '-ro': ro = True elif argv[i] == '-a_srs' and i < len(argv) - 1: srs = argv[i + 1] i = i + 1 elif argv[i] == '-a_ullr' and i < len(argv) - 4: ulx = float(argv[i + 1]) i = i + 1 uly = float(argv[i + 1]) i = i + 1 lrx = float(argv[i + 1]) i = i + 1 lry = float(argv[i + 1]) i = i + 1 elif argv[i] == '-tr' and i < len(argv) - 2: xres = float(argv[i + 1]) i = i + 1 yres = float(argv[i + 1]) i = i + 1 elif argv[i] == '-a_nodata' and i < len(argv) - 1: nodata = float(argv[i + 1]) i = i + 1 elif argv[i] == '-mo' and i < len(argv) - 1: molist.append(argv[i + 1]) i = i + 1 elif argv[i] == '-gcp' and i + 4 < len(argv): pixel = float(argv[i + 1]) i = i + 1 line = float(argv[i + 1]) i = i + 1 x = float(argv[i + 1]) i = i + 1 y = float(argv[i + 1]) i = i + 1 if i + 1 < len(argv) and ArgIsNumeric(argv[i + 1]): z = float(argv[i + 1]) i = i + 1 else: z = 0 gcp = gdal.GCP(x, y, z, pixel, line) gcp_list.append(gcp) elif argv[i] == '-unsetgt': unsetgt = True elif argv[i][0] == '-': sys.stderr.write('Unrecognized option : %s\n' % argv[i]) return Usage() elif datasetname is None: datasetname = argv[i] else: sys.stderr.write('Unexpected option : %s\n' % argv[i]) return Usage() i = i + 1 if datasetname is None: return Usage() if srs is None and lry is None and yres is None and not unsetgt and nodata is None and len( molist) == 0: print('No option specified') print('') return Usage() exclusive_option = 0 if lry is not None: exclusive_option = exclusive_option + 1 if yres is not None: exclusive_option = exclusive_option + 1 if unsetgt: exclusive_option = exclusive_option + 1 if exclusive_option > 1: print('-a_ullr, -tr and -unsetgt options are exclusive.') print('') return Usage() if ro: ds = gdal.Open(datasetname) else: ds = gdal.Open(datasetname, gdal.GA_Update) if ds is None: return -1 wkt = None if srs == '' or srs == 'None': ds.SetProjection('') elif srs is not None: sr = osr.SpatialReference() if sr.SetFromUserInput(srs) != 0: print('Failed to process SRS definition: %s' % srs) return -1 wkt = sr.ExportToWkt() if len(gcp_list) == 0: ds.SetProjection(wkt) if lry is not None: gt = [ ulx, (lrx - ulx) / ds.RasterXSize, 0, uly, 0, (lry - uly) / ds.RasterYSize ] ds.SetGeoTransform(gt) if yres is not None: gt = ds.GetGeoTransform() # Doh ! why is gt a tuple and not an array... gt = [gt[i] for i in range(6)] gt[1] = xres gt[5] = yres ds.SetGeoTransform(gt) if unsetgt: ds.SetGeoTransform([0, 1, 0, 0, 0, 1]) if len(gcp_list) > 0: if wkt is None: wkt = ds.GetGCPProjection() if wkt is None: wkt = '' ds.SetGCPs(gcp_list, wkt) if nodata is not None: for i in range(ds.RasterCount): ds.GetRasterBand(1).SetNoDataValue(nodata) if len(molist) != 0: ds.SetMetadata(molist) ds = None return 0
def main(argv): frmt = None options = [] quiet_flag = 0 src_filename = None src_band_n = 1 dst_filename = None dst_layername = None dst_fieldname = None dst_field = -1 mask = 'default' argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 0 # Parse command line arguments. i = 1 while i < len(argv): arg = argv[i] if arg == '-f' or arg == '-of': i = i + 1 frmt = argv[i] elif arg == '-q' or arg == '-quiet': quiet_flag = 1 elif arg == '-8': options.append('8CONNECTED=8') elif arg == '-nomask': mask = 'none' elif arg == '-mask': i = i + 1 mask = argv[i] elif arg == '-b': i = i + 1 if argv[i].startswith('mask'): src_band_n = argv[i] else: src_band_n = int(argv[i]) elif src_filename is None: src_filename = argv[i] elif dst_filename is None: dst_filename = argv[i] elif dst_layername is None: dst_layername = argv[i] elif dst_fieldname is None: dst_fieldname = argv[i] else: return Usage() i = i + 1 if src_filename is None or dst_filename is None: return Usage() if frmt is None: frmt = GetOutputDriverFor(dst_filename, is_raster=False) if dst_layername is None: dst_layername = 'out' # ============================================================================= # Verify we have next gen bindings with the polygonize method. # ============================================================================= try: gdal.Polygonize except AttributeError: print('') print( 'gdal.Polygonize() not available. You are likely using "old gen"') print('bindings or an older version of the next gen bindings.') print('') return 1 # ============================================================================= # Open source file # ============================================================================= src_ds = gdal.Open(src_filename) if src_ds is None: print('Unable to open %s' % src_filename) return 1 if src_band_n == 'mask': srcband = src_ds.GetRasterBand(1).GetMaskBand() # Workaround the fact that most source bands have no dataset attached options.append('DATASET_FOR_GEOREF=' + src_filename) elif isinstance(src_band_n, str) and src_band_n.startswith('mask,'): srcband = src_ds.GetRasterBand(int( src_band_n[len('mask,'):])).GetMaskBand() # Workaround the fact that most source bands have no dataset attached options.append('DATASET_FOR_GEOREF=' + src_filename) else: srcband = src_ds.GetRasterBand(src_band_n) if mask == 'default': maskband = srcband.GetMaskBand() elif mask == 'none': maskband = None else: mask_ds = gdal.Open(mask) maskband = mask_ds.GetRasterBand(1) # ============================================================================= # Try opening the destination file as an existing file. # ============================================================================= try: gdal.PushErrorHandler('CPLQuietErrorHandler') dst_ds = ogr.Open(dst_filename, update=1) gdal.PopErrorHandler() except: dst_ds = None # ============================================================================= # Create output file. # ============================================================================= if dst_ds is None: drv = ogr.GetDriverByName(frmt) if not quiet_flag: print('Creating output %s of format %s.' % (dst_filename, frmt)) dst_ds = drv.CreateDataSource(dst_filename) # ============================================================================= # Find or create destination layer. # ============================================================================= try: dst_layer = dst_ds.GetLayerByName(dst_layername) except: dst_layer = None if dst_layer is None: srs = src_ds.GetSpatialRef() dst_layer = dst_ds.CreateLayer(dst_layername, geom_type=ogr.wkbPolygon, srs=srs) if dst_fieldname is None: dst_fieldname = 'DN' fd = ogr.FieldDefn(dst_fieldname, ogr.OFTInteger) dst_layer.CreateField(fd) dst_field = 0 else: if dst_fieldname is not None: dst_field = dst_layer.GetLayerDefn().GetFieldIndex(dst_fieldname) if dst_field < 0: print("Warning: cannot find field '%s' in layer '%s'" % (dst_fieldname, dst_layername)) # ============================================================================= # Invoke algorithm. # ============================================================================= if quiet_flag: prog_func = None else: prog_func = gdal.TermProgress_nocb result = gdal.Polygonize(srcband, maskband, dst_layer, dst_field, options, callback=prog_func) srcband = None src_ds = None dst_ds = None mask_ds = None return result
def main(argv=sys.argv): # Default GDAL argument parsing. argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 0 if len(argv) == 1: return Usage(brief=0) # Script argument defaults src_crs_id = None src_crs_date = None dst_crs_id = None dst_crs_date = None # Decent representation of continental US griddef = (-127.0, 50.0, -66.0, 25.0, 611, 251) htdp_path = 'htdp' wrkdir = '.' kwf = 0 output_grid_name = None # Script argument parsing. i = 1 while i < len(argv): if argv[i] == '-griddef' and i < len(argv) - 6: griddef = (float(argv[i + 1]), float(argv[i + 2]), float(argv[i + 3]), float(argv[i + 4]), float(argv[i + 5]), float(argv[i + 6])) i = i + 6 elif argv[i] == '-htdp' and i < len(argv) - 1: htdp_path = argv[i + 1] i = i + 1 elif argv[i] == '-kwf': kwf = 1 elif argv[i] == '-wrkdir' and i < len(argv) - 1: wrkdir = argv[i + 1] i = i + 1 elif argv[i] == '-o' and i < len(argv) - 1: output_grid_name = argv[i + 1] i = i + 1 elif argv[i] == '-h' or argv[i] == '--help': return Usage(brief=0) elif argv[i][0] == '-': print('Urecognised argument: ' + argv[i]) return Usage() elif src_crs_id is None: src_crs_id = int(argv[i]) elif src_crs_date is None: src_crs_date = argv[i] elif dst_crs_id is None: dst_crs_id = int(argv[i]) elif dst_crs_date is None: dst_crs_date = argv[i] else: print('Urecognised argument: ' + argv[i]) return Usage() i = i + 1 # next argument if output_grid_name is None: print('Missing output grid name (-o)') return Usage() if dst_crs_date is None: print('Source and Destination CRS Ids and Dates are mandatory, ' 'not all provided.') return Usage() # Do a bit of validation of parameters. if src_crs_id < 1 or src_crs_id > 32 \ or dst_crs_id < 1 or dst_crs_id > 32: print('Invalid source or destination CRS Id %d and %d.' % (src_crs_id, dst_crs_id)) return Usage(brief=0) if float(src_crs_date) < 1700.0 or float(src_crs_date) > 2300.0 \ or float(dst_crs_date) < 1700.0 or float(dst_crs_date) > 2300.0: print('Source or destination CRS date seems odd %s and %s.' % (src_crs_date, dst_crs_date)) return Usage(brief=0) # Prepare out set of working file names. in_grid_fn = wrkdir + '/crs2crs_input.txt' out_grid_fn = wrkdir + '/crs2crs_output.txt' control_fn = wrkdir + '/crs2crs_control.txt' # Write out the source grid file. grid = new_create_grid(griddef) write_grid(grid, in_grid_fn) write_control(control_fn, out_grid_fn, in_grid_fn, src_crs_id, src_crs_date, dst_crs_id, dst_crs_date) # Run htdp to transform the data. try: os.unlink(out_grid_fn) except OSError: pass rc = os.system(htdp_path + ' < ' + control_fn) if rc != 0: print('htdp run failed!') return 1 print('htdp run complete.') adjustment = read_grid_crs_to_crs(out_grid_fn, grid.shape) if adjustment is None: return 1 # Convert shifts to radians adjustment = adjustment * (3.14159265358979323846 / 180.0) # write to output output grid file. write_gdal_grid(output_grid_name, adjustment, griddef) # cleanup working files unless they have been requested to remain. if kwf == 0: os.unlink(in_grid_fn) os.unlink(out_grid_fn) os.unlink(control_fn) print('Processing complete: see ' + output_grid_name) return 0
def handlecmd(argv=None): import optparse if argv is None: argv = sys.argv argv = gdal.GeneralCmdLineProcessor(argv) parser = optparse.OptionParser( usage='%prog [options] FILENAME', version='%%prog %s' % __version__, description=__doc__) parser.add_option('--no-stats', dest='stats', action='store_false', default=True, help='disable statistics computation (default: False)') parser.add_option('--hist', action='store_true', default=False, help='enable histogram computation (default: %default)') parser.add_option('-b', '--band', type='int', help='compute statistics for a specific raster band ' '(default: all bands are precessed)') parser.add_option('-a', '--approxok', action='store_true', default=False, help='if set then statistics may be computed based on ' 'overviews or a subset of all tiles ' '(default: %default)') parser.add_option('--minmax-only', action='store_true', default=False, help='only print minimum and maximum on the same line.') parser.add_option('--histreq', nargs=3, type='float', metavar='MIN MAX NBUCKETS', help='specify lower bound, upper bound and the number ' 'of buckets for histogram computation ' '(automatically computed otherwise)') parser.add_option('-i', '--include_out_of_range', action='store_true', default=False, help='if set then values below the histogram range will ' 'be mapped into the first bucket, and values above ' 'will be mapped into last one. ' 'Otherwise out of range values are discarded.') parser.add_option('--srcwin', nargs=4, type='int', metavar='XOFFSET YOFFSET XSIZE YSIZE', help='specify source window in image coordinates: ' '(default: the entire image is processed)') parser.add_option('-o', '--outfile', metavar='FILE', help='write results to FILE (default: stdout)', ) parser.add_option('-q', '--quiet', action='store_true', help='suppress progress messages') options, args = parser.parse_args() if options.histreq and not options.hist: options.hist = True #parser.error('"histreq" option requires "hist"') if options.include_out_of_range and not options.hist: parser.error('"include_out_of_range" option requires "hist"') if options.band is not None and options.band < 1: parser.error('the "band" parameter shoulb be a not null positive ' 'integer.') histonly = bool(options.hist and not options.stats) if histonly and options.approxok and not options.histreq: logging.warning('the "approxok" option is ignored if "histreq" ' 'is not set.') if not options.stats and not options.hist: parser.error('nothing to compute: ' 'please check "--hist" and "--no-stats" optoions.') if len(args) != 1: parser.error('at least one argument is required.') return options, args
def main(argv): threshold = 2 connectedness = 4 quiet_flag = 0 src_filename = None dst_filename = None frmt = None mask = 'default' argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 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 == '-4': connectedness = 4 elif arg == '-8': connectedness = 8 elif arg == '-q' or arg == '-quiet': quiet_flag = 1 elif arg == '-st': i = i + 1 threshold = int(argv[i]) elif arg == '-nomask': mask = 'none' elif arg == '-mask': i = i + 1 mask = argv[i] elif arg == '-mask': i = i + 1 mask = argv[i] elif arg[:2] == '-h': return Usage() elif src_filename is None: src_filename = argv[i] elif dst_filename is None: dst_filename = argv[i] else: return Usage() i = i + 1 if src_filename is None: return Usage() # ============================================================================= # Verify we have next gen bindings with the sievefilter method. # ============================================================================= try: gdal.SieveFilter except AttributeError: print('') print( 'gdal.SieveFilter() not available. You are likely using "old gen"' ) print('bindings or an older version of the next gen bindings.') print('') return 1 # ============================================================================= # Open source file # ============================================================================= if dst_filename is None: src_ds = gdal.Open(src_filename, gdal.GA_Update) else: src_ds = gdal.Open(src_filename, gdal.GA_ReadOnly) if src_ds is None: print('Unable to open %s ' % src_filename) return 1 srcband = src_ds.GetRasterBand(1) if mask == 'default': maskband = srcband.GetMaskBand() elif mask == 'none': maskband = None else: mask_ds = gdal.Open(mask) maskband = mask_ds.GetRasterBand(1) # ============================================================================= # Create output file if one is specified. # ============================================================================= if dst_filename is not 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, srcband.DataType) wkt = src_ds.GetProjection() if wkt != '': dst_ds.SetProjection(wkt) gt = src_ds.GetGeoTransform(can_return_null=True) if gt is not None: dst_ds.SetGeoTransform(gt) dstband = dst_ds.GetRasterBand(1) else: dstband = srcband # ============================================================================= # Invoke algorithm. # ============================================================================= if quiet_flag: prog_func = None else: prog_func = gdal.TermProgress_nocb result = gdal.SieveFilter(srcband, maskband, dstband, threshold, connectedness, callback=prog_func) src_ds = None dst_ds = None mask_ds = None return result
def main(argv=sys.argv): gdal.GeneralCmdLineProcessor(argv) return jpeg_in_tiff_extract(argv[1:])
def main(argv=sys.argv): argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return -1 pan_name = None spectral_names = [] spectral_ds = [] spectral_bands = [] band_nums = [] weights = [] driver_name = None creation_options = [] progress_callback = gdal.TermProgress_nocb resampling = None spat_adjust = None verbose_vrt = False num_threads = None bitdepth = None nodata_value = None i = 1 argc = len(argv) while i < argc: if (argv[i] == '-of' or argv[i] == '-f') and i < len(argv) - 1: driver_name = argv[i + 1] i = i + 1 elif argv[i] == '-r' and i < len(argv) - 1: resampling = argv[i + 1] i = i + 1 elif argv[i] == '-spat_adjust' and i < len(argv) - 1: spat_adjust = argv[i + 1] i = i + 1 elif argv[i] == '-b' and i < len(argv) - 1: band_nums.append(int(argv[i + 1])) i = i + 1 elif argv[i] == '-w' and i < len(argv) - 1: weights.append(float(argv[i + 1])) i = i + 1 elif argv[i] == '-co' and i < len(argv) - 1: creation_options.append(argv[i + 1]) i = i + 1 elif argv[i] == '-threads' and i < len(argv) - 1: num_threads = argv[i + 1] i = i + 1 elif argv[i] == '-bitdepth' and i < len(argv) - 1: bitdepth = argv[i + 1] i = i + 1 elif argv[i] == '-nodata' and i < len(argv) - 1: nodata_value = argv[i + 1] i = i + 1 elif argv[i] == '-q': progress_callback = None elif argv[i] == '-verbose_vrt': verbose_vrt = True elif argv[i][0] == '-': sys.stderr.write('Unrecognized option : %s\n' % argv[i]) return Usage() elif pan_name is None: pan_name = argv[i] else: spectral_names.append(argv[i]) i = i + 1 if pan_name is None or len(spectral_names) < 2: return Usage() dst_filename = spectral_names.pop() return gdal_pansharpen(argv=None, pan_name=pan_name, spectral_names=spectral_names, spectral_ds=spectral_ds, spectral_bands=spectral_bands, band_nums=band_nums, weights=weights, dst_filename=dst_filename, driver_name=driver_name, creation_options=creation_options, resampling=resampling, spat_adjust=spat_adjust, num_threads=num_threads, bitdepth=bitdepth, nodata_value=nodata_value, verbose_vrt=verbose_vrt, progress_callback=progress_callback)
def main(argv=None): print('Now in main!') bComputeMinMax = False bSample = False bShowGCPs = True bShowMetadata = False bShowRAT = False debug = False bStats = False bApproxStats = True bShowColorTable = True bComputeChecksum = False bReportHistograms = False pszFilename = None papszExtraMDDomains = [] pszProjection = None hTransform = None bShowFileList = True dst_img = None dst_lbl = None bands = 1 #/* Must process GDAL_SKIP before GDALAllRegister(), but we can't call */ #/* GDALGeneralCmdLineProcessor before it needs the drivers to be registered */ #/* for the --format or --formats options */ #for( i = 1; i < argc; i++ ) #{ # if EQUAL(argv[i],"--config") and i + 2 < argc and EQUAL(argv[i + 1], "GDAL_SKIP"): # { # CPLSetConfigOption( argv[i+1], argv[i+2] ); # # i += 2; # } #} # #GDALAllRegister(); if argv is None: argv = sys.argv argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 1 nArgc = len(argv) #/* -------------------------------------------------------------------- */ #/* Parse arguments. */ #/* -------------------------------------------------------------------- */ i = 1 while i < nArgc: if EQUAL(argv[i], "--utility_version"): print("%s is running against GDAL %s" % (argv[0], gdal.VersionInfo("RELEASE_NAME"))) return 0 elif EQUAL(argv[i], "-debug"): debug = True elif EQUAL(argv[i], "-mm"): bComputeMinMax = True elif EQUAL(argv[i], "-hist"): bReportHistograms = True elif EQUAL(argv[i], "-stats"): bStats = True bApproxStats = False elif EQUAL(argv[i], "-approx_stats"): bStats = True bApproxStats = True elif EQUAL(argv[i], "-sample"): bSample = True elif EQUAL(argv[i], "-checksum"): bComputeChecksum = True elif EQUAL(argv[i], "-nogcp"): bShowGCPs = False elif EQUAL(argv[i], "-nomd"): bShowMetadata = False elif EQUAL(argv[i], "-norat"): bShowRAT = False elif EQUAL(argv[i], "-noct"): bShowColorTable = False elif EQUAL(argv[i], "-mdd") and i < nArgc - 1: i = i + 1 papszExtraMDDomains.append(argv[i]) elif EQUAL(argv[i], "-nofl"): bShowFileList = False elif argv[i][0] == '-': return Usage(argv[0]) elif pszFilename is None: pszFilename = argv[i] elif dst_img is None: dst_img = argv[i] else: return Usage(argv[0]) i = i + 1 if pszFilename is None: return Usage(argv[0]) if dst_img is None: return Usage(argv[0]) #/* -------------------------------------------------------------------- */ #/* Open dataset. */ #/* -------------------------------------------------------------------- */ hDataset = gdal.Open(pszFilename, gdal.GA_ReadOnly) if hDataset is None: print("gdalinfo failed - unable to open '%s'." % pszFilename) sys.exit(1) # Open the output file. if dst_img is not None: dst_lbl = dst_img.replace("IMG", "LBL") dst_lbl = dst_lbl.replace("img", "lbl") if (EQUAL(dst_lbl, dst_img)): print( 'Extension must be .IMG or .img - unable to run using filename: %s' % pszFilename) sys.exit(1) else: f = open(dst_lbl, 'wt') # else: # f = sys.stdout # dst_img = "out.img" #/* -------------------------------------------------------------------- */ #/* Report general info. */ #/* -------------------------------------------------------------------- */ hDriver = hDataset.GetDriver() if debug: print( "Driver: %s/%s" % ( \ hDriver.ShortName, \ hDriver.LongName )) papszFileList = hDataset.GetFileList() if papszFileList is None or len(papszFileList) == 0: print("Files: none associated") else: if debug: print("Files: %s" % papszFileList[0]) if bShowFileList: for i in range(1, len(papszFileList)): print(" %s" % papszFileList[i]) if debug: print("Size is %d, %d" % (hDataset.RasterXSize, hDataset.RasterYSize)) #/* -------------------------------------------------------------------- */ #/* Report projection. */ #/* -------------------------------------------------------------------- */ pszProjection = hDataset.GetProjectionRef() if pszProjection is not None: hSRS = osr.SpatialReference() if hSRS.ImportFromWkt(pszProjection) == gdal.CE_None: pszPrettyWkt = hSRS.ExportToPrettyWkt(False) #print( "Coordinate System is:\n%s" % pszPrettyWkt ) mapProjection = "None" #Extract projection information target = hSRS.GetAttrValue("DATUM", 0).replace("D_", "").replace("_2000", "") semiMajor = hSRS.GetSemiMajor() / 1000.0 semiMinor = hSRS.GetSemiMinor() / 1000.0 if (pszProjection[0:6] == "GEOGCS"): mapProjection = "SIMPLE_CYLINDRICAL" centLat = 0 centLon = 0 if (pszProjection[0:6] == "PROJCS"): mapProjection = hSRS.GetAttrValue("PROJECTION", 0) if EQUAL(mapProjection, "Equirectangular"): centLat = hSRS.GetProjParm('standard_parallel_1') centLon = hSRS.GetProjParm('central_meridian') if EQUAL(mapProjection, "Polar_Stereographic"): centLat = hSRS.GetProjParm('latitude_of_origin') centLon = hSRS.GetProjParm('central_meridian') if EQUAL(mapProjection, "Stereographic_South_Pole"): centLat = hSRS.GetProjParm('latitude_of_origin') centLon = hSRS.GetProjParm('central_meridian') if EQUAL(mapProjection, "Stereographic_North_Pole"): centLat = hSRS.GetProjParm('latitude_of_origin') centLon = hSRS.GetProjParm('central_meridian') if debug: print("Coordinate System is:\n%s" % pszPrettyWkt) else: print("Warning - Can't parse this type of projection\n") print("Coordinate System is `%s'" % pszProjection) sys.exit(1) else: print("Warning - No Coordinate System defined:\n") sys.exit(1) #/* -------------------------------------------------------------------- */ #/* Report Geotransform. */ #/* -------------------------------------------------------------------- */ adfGeoTransform = hDataset.GetGeoTransform(can_return_null=True) if adfGeoTransform is not None: if adfGeoTransform[2] == 0.0 and adfGeoTransform[4] == 0.0: if debug: print( "Origin = (%.15f,%.15f)" % ( \ adfGeoTransform[0], adfGeoTransform[3] )) print( "Pixel Size = (%.15f,%.15f)" % ( \ adfGeoTransform[1], adfGeoTransform[5] )) else: if debug: print( "GeoTransform =\n" \ " %.16g, %.16g, %.16g\n" \ " %.16g, %.16g, %.16g" % ( \ adfGeoTransform[0], \ adfGeoTransform[1], \ adfGeoTransform[2], \ adfGeoTransform[3], \ adfGeoTransform[4], \ adfGeoTransform[5] )) if (pszProjection[0:6] == "GEOGCS"): #convert degrees/pixel to km/pixel mapres = 1 / adfGeoTransform[1] kmres = adfGeoTransform[1] * (semiMajor * math.pi / 180.0) else: #convert m/pixel to pixel/degree mapres = 1 / (adfGeoTransform[1] / (semiMajor * 1000.0 * math.pi / 180.0)) kmres = adfGeoTransform[1] / 1000.0 #/* -------------------------------------------------------------------- */ #/* Report GCPs. */ #/* -------------------------------------------------------------------- */ if bShowGCPs and hDataset.GetGCPCount() > 0: pszProjection = hDataset.GetGCPProjection() if pszProjection is not None: hSRS = osr.SpatialReference() if hSRS.ImportFromWkt(pszProjection) == gdal.CE_None: pszPrettyWkt = hSRS.ExportToPrettyWkt(False) if debug: print("GCP Projection = \n%s" % pszPrettyWkt) else: if debug: print( "GCP Projection = %s" % \ pszProjection ) gcps = hDataset.GetGCPs() i = 0 for gcp in gcps: if debug: print( "GCP[%3d]: Id=%s, Info=%s\n" \ " (%.15g,%.15g) -> (%.15g,%.15g,%.15g)" % ( \ i, gcp.Id, gcp.Info, \ gcp.GCPPixel, gcp.GCPLine, \ gcp.GCPX, gcp.GCPY, gcp.GCPZ )) i = i + 1 #/* -------------------------------------------------------------------- */ #/* Report metadata. */ #/* -------------------------------------------------------------------- */ if debug: if bShowMetadata: papszMetadata = hDataset.GetMetadata_List() else: papszMetadata = None if bShowMetadata and papszMetadata is not None and len( papszMetadata) > 0: print("Metadata:") for metadata in papszMetadata: print(" %s" % metadata) if bShowMetadata: for extra_domain in papszExtraMDDomains: papszMetadata = hDataset.GetMetadata_List(extra_domain) if papszMetadata is not None and len(papszMetadata) > 0: print("Metadata (%s):" % extra_domain) for metadata in papszMetadata: print(" %s" % metadata) #/* -------------------------------------------------------------------- */ #/* Report "IMAGE_STRUCTURE" metadata. */ #/* -------------------------------------------------------------------- */ if bShowMetadata: papszMetadata = hDataset.GetMetadata_List("IMAGE_STRUCTURE") else: papszMetadata = None if bShowMetadata and papszMetadata is not None and len( papszMetadata) > 0: print("Image Structure Metadata:") for metadata in papszMetadata: print(" %s" % metadata) #/* -------------------------------------------------------------------- */ #/* Report subdatasets. */ #/* -------------------------------------------------------------------- */ papszMetadata = hDataset.GetMetadata_List("SUBDATASETS") if papszMetadata is not None and len(papszMetadata) > 0: print("Subdatasets:") for metadata in papszMetadata: print(" %s" % metadata) #/* -------------------------------------------------------------------- */ #/* Report geolocation. */ #/* -------------------------------------------------------------------- */ if bShowMetadata: papszMetadata = hDataset.GetMetadata_List("GEOLOCATION") else: papszMetadata = None if bShowMetadata and papszMetadata is not None and len( papszMetadata) > 0: print("Geolocation:") for metadata in papszMetadata: print(" %s" % metadata) #/* -------------------------------------------------------------------- */ #/* Report RPCs */ #/* -------------------------------------------------------------------- */ if bShowMetadata: papszMetadata = hDataset.GetMetadata_List("RPC") else: papszMetadata = None if bShowMetadata and papszMetadata is not None and len( papszMetadata) > 0: print("RPC Metadata:") for metadata in papszMetadata: print(" %s" % metadata) #/* -------------------------------------------------------------------- */ #/* Setup projected to lat/long transform if appropriate. */ #/* -------------------------------------------------------------------- */ if pszProjection is not None and len(pszProjection) > 0: hProj = osr.SpatialReference(pszProjection) if hProj is not None: hLatLong = hProj.CloneGeogCS() if hLatLong is not None: gdal.PushErrorHandler('CPLQuietErrorHandler') hTransform = osr.CoordinateTransformation(hProj, hLatLong) gdal.PopErrorHandler() if gdal.GetLastErrorMsg().find( 'Unable to load PROJ.4 library') != -1: hTransform = None #/* -------------------------------------------------------------------- */ #/* Report corners. */ #/* -------------------------------------------------------------------- */ if debug: print("Corner Coordinates:") GDALInfoReportCorner( hDataset, hTransform, "Upper Left", \ 0.0, 0.0 ) GDALInfoReportCorner( hDataset, hTransform, "Lower Left", \ 0.0, hDataset.RasterYSize) GDALInfoReportCorner( hDataset, hTransform, "Upper Right", \ hDataset.RasterXSize, 0.0 ) GDALInfoReportCorner( hDataset, hTransform, "Lower Right", \ hDataset.RasterXSize, \ hDataset.RasterYSize ) GDALInfoReportCorner( hDataset, hTransform, "Center", \ hDataset.RasterXSize/2.0, \ hDataset.RasterYSize/2.0 ) #Get bounds ulx = GDALGetLon(hDataset, hTransform, 0.0, 0.0) uly = GDALGetLat(hDataset, hTransform, 0.0, 0.0) lrx = GDALGetLon( hDataset, hTransform, hDataset.RasterXSize, \ hDataset.RasterYSize ) lry = GDALGetLat( hDataset, hTransform, hDataset.RasterXSize, \ hDataset.RasterYSize ) #/* ==================================================================== */ #/* Loop over bands. */ #/* ==================================================================== */ if debug: bands = hDataset.RasterCount for iBand in range(hDataset.RasterCount): hBand = hDataset.GetRasterBand(iBand + 1) #if( bSample ) #{ # float afSample[10000]; # int nCount; # # nCount = GDALGetRandomRasterSample( hBand, 10000, afSample ); # print( "Got %d samples.\n", nCount ); #} (nBlockXSize, nBlockYSize) = hBand.GetBlockSize() print( "Band %d Block=%dx%d Type=%s, ColorInterp=%s" % ( iBand+1, \ nBlockXSize, nBlockYSize, \ gdal.GetDataTypeName(hBand.DataType), \ gdal.GetColorInterpretationName( \ hBand.GetRasterColorInterpretation()) )) if hBand.GetDescription() is not None \ and len(hBand.GetDescription()) > 0 : print(" Description = %s" % hBand.GetDescription()) dfMin = hBand.GetMinimum() dfMax = hBand.GetMaximum() if dfMin is not None or dfMax is not None or bComputeMinMax: line = " " if dfMin is not None: line = line + ("Min=%.3f " % dfMin) if dfMax is not None: line = line + ("Max=%.3f " % dfMax) if bComputeMinMax: gdal.ErrorReset() adfCMinMax = hBand.ComputeRasterMinMax(False) if gdal.GetLastErrorType() == gdal.CE_None: line = line + ( " Computed Min/Max=%.3f,%.3f" % ( \ adfCMinMax[0], adfCMinMax[1] )) print(line) stats = hBand.GetStatistics(bApproxStats, bStats) # Dirty hack to recognize if stats are valid. If invalid, the returned # stddev is negative if stats[3] >= 0.0: print( " Minimum=%.3f, Maximum=%.3f, Mean=%.3f, StdDev=%.3f" % ( \ stats[0], stats[1], stats[2], stats[3] )) if bReportHistograms: hist = hBand.GetDefaultHistogram(force=True, callback=gdal.TermProgress) if hist is not None: dfMin = hist[0] dfMax = hist[1] nBucketCount = hist[2] panHistogram = hist[3] print( " %d buckets from %g to %g:" % ( \ nBucketCount, dfMin, dfMax )) line = ' ' for bucket in panHistogram: line = line + ("%d " % bucket) print(line) if bComputeChecksum: print(" Checksum=%d" % hBand.Checksum()) dfNoData = hBand.GetNoDataValue() if dfNoData is not None: if dfNoData != dfNoData: print(" NoData Value=nan") else: print(" NoData Value=%.18g" % dfNoData) if hBand.GetOverviewCount() > 0: line = " Overviews: " for iOverview in range(hBand.GetOverviewCount()): if iOverview != 0: line = line + ", " hOverview = hBand.GetOverview(iOverview) if hOverview is not None: line = line + ("%dx%d" % (hOverview.XSize, hOverview.YSize)) pszResampling = \ hOverview.GetMetadataItem( "RESAMPLING", "" ) if pszResampling is not None \ and len(pszResampling) >= 12 \ and EQUAL(pszResampling[0:12],"AVERAGE_BIT2"): line = line + "*" else: line = line + "(null)" print(line) if bComputeChecksum: line = " Overviews checksum: " for iOverview in range(hBand.GetOverviewCount()): if iOverview != 0: line = line + ", " hOverview = hBand.GetOverview(iOverview) if hOverview is not None: line = line + ("%d" % hOverview.Checksum()) else: line = line + "(null)" print(line) if hBand.HasArbitraryOverviews(): print(" Overviews: arbitrary") nMaskFlags = hBand.GetMaskFlags() if (nMaskFlags & (gdal.GMF_NODATA | gdal.GMF_ALL_VALID)) == 0: hMaskBand = hBand.GetMaskBand() line = " Mask Flags: " if (nMaskFlags & gdal.GMF_PER_DATASET) != 0: line = line + "PER_DATASET " if (nMaskFlags & gdal.GMF_ALPHA) != 0: line = line + "ALPHA " if (nMaskFlags & gdal.GMF_NODATA) != 0: line = line + "NODATA " if (nMaskFlags & gdal.GMF_ALL_VALID) != 0: line = line + "ALL_VALID " print(line) if hMaskBand is not None and \ hMaskBand.GetOverviewCount() > 0: line = " Overviews of mask band: " for iOverview in range(hMaskBand.GetOverviewCount()): if iOverview != 0: line = line + ", " hOverview = hMaskBand.GetOverview(iOverview) if hOverview is not None: line = line + ("%d" % hOverview.Checksum()) else: line = line + "(null)" if len(hBand.GetUnitType()) > 0: print(" Unit Type: %s" % hBand.GetUnitType()) papszCategories = hBand.GetRasterCategoryNames() if papszCategories is not None: print(" Categories:") i = 0 for category in papszCategories: print(" %3d: %s" % (i, category)) i = i + 1 if hBand.GetScale() != 1.0 or hBand.GetOffset() != 0.0: print( " Offset: %.15g, Scale:%.15g" % \ ( hBand.GetOffset(), hBand.GetScale())) if bShowMetadata: papszMetadata = hBand.GetMetadata_List() else: papszMetadata = None if bShowMetadata and papszMetadata is not None and len( papszMetadata) > 0: print(" Metadata:") for metadata in papszMetadata: print(" %s" % metadata) if bShowMetadata: papszMetadata = hBand.GetMetadata_List("IMAGE_STRUCTURE") else: papszMetadata = None if bShowMetadata and papszMetadata is not None and len( papszMetadata) > 0: print(" Image Structure Metadata:") for metadata in papszMetadata: print(" %s" % metadata) hTable = hBand.GetRasterColorTable() if hBand.GetRasterColorInterpretation() == gdal.GCI_PaletteIndex \ and hTable is not None: print( " Color Table (%s with %d entries)" % (\ gdal.GetPaletteInterpretationName( \ hTable.GetPaletteInterpretation( )), \ hTable.GetCount() )) if bShowColorTable: for i in range(hTable.GetCount()): sEntry = hTable.GetColorEntry(i) print( " %3d: %d,%d,%d,%d" % ( \ i, \ sEntry[0],\ sEntry[1],\ sEntry[2],\ sEntry[3] )) if bShowRAT: hRAT = hBand.GetDefaultRAT() #GDALRATDumpReadable( hRAT, None ); #/************************************************************************/ #/* WritePDSlabel() */ #/************************************************************************/ #def WritePDSlabel(outFile, DataSetID, pszFilename, sampleBits, lines, samples): instrList = pszFilename.split("_") hBand = hDataset.GetRasterBand(1) #get the datatype if EQUAL(gdal.GetDataTypeName(hBand.DataType), "Float32"): sample_bits = 32 sample_type = "PC_REAL" sample_mask = "2#11111111111111111111111111111111#" elif EQUAL(gdal.GetDataTypeName(hBand.DataType), "INT16"): sample_bits = 16 sample_type = "LSB_INTEGER" sample_mask = "2#1111111111111111#" elif EQUAL(gdal.GetDataTypeName(hBand.DataType), "UINT16"): sample_bits = 16 sample_type = "UNSIGNED_INTEGER" sample_mask = "2#1111111111111111#" elif EQUAL(gdal.GetDataTypeName(hBand.DataType), "Byte"): sample_bits = 8 sample_type = "UNSIGNED_INTEGER" sample_mask = "2#11111111#" else: print(" %s: Not supported pixel type" % gdal.GetDataTypeName(hBand.DataType)) sys.exit(1) f.write('PDS_VERSION_ID = PDS3\n') f.write('\n') f.write('/* The source image data definition. */\n') f.write('FILE_NAME = \"%s\"\n' % (dst_img)) f.write('RECORD_TYPE = FIXED_LENGTH\n') f.write('RECORD_BYTES = %d\n' % (hDataset.RasterYSize)) f.write('FILE_RECORDS = %d\n' % ((hDataset.RasterXSize * sample_bits / 8))) #f.write('LABEL_RECORDS = 1\n') f.write('^IMAGE = \"%s\"\n' % (dst_img)) f.write('\n') f.write('/* Identification Information */\n') f.write('DATA_SET_ID = "%s"\n' % pszFilename.split(".")[0]) f.write('DATA_SET_NAME = "%s"\n' % pszFilename.split(".")[0]) f.write( 'PRODUCER_INSTITUTION_NAME = "Lunar Mapping and Modeling Project"\n') f.write('PRODUCER_ID = "LMMP_TEAM"\n') f.write('PRODUCER_FULL_NAME = "LMMP TEAM"\n') f.write('PRODUCT_ID = "%s"\n' % pszFilename.split(".")[0]) if "_v" in pszFilename: f.write('PRODUCT_VERSION_ID = "%s.0"\n' % instrList[-1].split(".")[0].upper()) else: f.write('PRODUCT_VERSION_ID = "%s"\n' % "V1.0") f.write('PRODUCT_TYPE = "RDR"\n') f.write('INSTRUMENT_HOST_NAME = "%s"\n' % instrList[0]) f.write('INSTRUMENT_HOST_ID = "%s"\n' % instrList[0]) f.write('INSTRUMENT_NAME = "%s"\n' % instrList[1]) f.write('INSTRUMENT_ID = "%s"\n' % instrList[1]) f.write('TARGET_NAME = MOON\n') f.write('MISSION_PHASE_NAME = "POST MISSION"\n') f.write( 'RATIONALE_DESC = "Created at the request of NASA\'s Exploration\n' ) f.write( ' Systems Mission Directorate to support future\n' ) f.write(' human exploration"\n') f.write( 'SOFTWARE_NAME = "ISIS 3.2.1 | SOCET SET v5.5 (r) BAE Systems\n' ) f.write(' | GDAL 1.8"\n') f.write('\n') f.write('/* Time Parameters */\n') f.write('START_TIME = "N/A"\n') f.write('STOP_TIME = "N/A"\n') f.write('SPACECRAFT_CLOCK_START_COUNT = "N/A"\n') f.write('SPACECRAFT_CLOCK_STOP_COUNT = "N/A"\n') f.write('PRODUCT_CREATION_TIME = %s\n' % strftime("%Y-%m-%dT%H:%M:%S")) #2011-03-11T22:13:40 f.write('\n') f.write('OBJECT = IMAGE_MAP_PROJECTION\n') f.write(' ^DATA_SET_MAP_PROJECTION = "DSMAP.CAT"\n') f.write(' MAP_PROJECTION_TYPE = \"%s\"\n' % mapProjection) f.write(' PROJECTION_LATITUDE_TYPE = PLANETOCENTRIC\n') f.write(' A_AXIS_RADIUS = %.1f <KM>\n' % semiMajor) f.write(' B_AXIS_RADIUS = %.1f <KM>\n' % semiMajor) f.write(' C_AXIS_RADIUS = %.1f <KM>\n' % semiMinor) f.write(' COORDINATE_SYSTEM_NAME = PLANETOCENTRIC\n') f.write(' POSITIVE_LONGITUDE_DIRECTION = EAST\n') f.write(' KEYWORD_LATITUDE_TYPE = PLANETOCENTRIC\n') f.write( ' /* NOTE: CENTER_LATITUDE and CENTER_LONGITUDE describe the location */\n' ) f.write( ' /* of the center of projection, which is not necessarily equal to the */\n' ) f.write( ' /* location of the center point of the image. */\n' ) f.write(' CENTER_LATITUDE = %5.2f <DEG>\n' % centLat) f.write(' CENTER_LONGITUDE = %5.2f <DEG>\n' % centLon) f.write(' LINE_FIRST_PIXEL = 1\n') f.write(' LINE_LAST_PIXEL = %d\n' % hDataset.RasterYSize) f.write(' SAMPLE_FIRST_PIXEL = 1\n') f.write(' SAMPLE_LAST_PIXEL = %d\n' % hDataset.RasterXSize) f.write(' MAP_PROJECTION_ROTATION = 0.0 <DEG>\n') f.write(' MAP_RESOLUTION = %.4f <PIX/DEG>\n' % mapres) f.write(' MAP_SCALE = %.8f <KM/PIXEL>\n' % kmres) f.write(' MINIMUM_LATITUDE = %.8f <DEGREE>\n' % lry) f.write(' MAXIMUM_LATITUDE = %.8f <DEGREE>\n' % uly) f.write(' WESTERNMOST_LONGITUDE = %.8f <DEGREE>\n' % ulx) f.write(' EASTERNMOST_LONGITUDE = %.8f <DEGREE>\n' % lrx) f.write(' LINE_PROJECTION_OFFSET = %.1f\n' % ((ulx / kmres * 1000) - 0.5)) f.write(' SAMPLE_PROJECTION_OFFSET = %.1f\n' % ((uly / kmres * 1000) + 0.5)) f.write('END_OBJECT = IMAGE_MAP_PROJECTION\n') f.write('\n') f.write('OBJECT = IMAGE\n') f.write(' NAME = \"%s\"\n' % (pszFilename)) f.write( ' DESCRIPTION = "Export data set from LMMP portal.\n' ) f.write(' see filename for data type."\n') #f.write('\n') f.write(' LINES = %d\n' % hDataset.RasterYSize) f.write(' LINE_SAMPLES = %d\n' % hDataset.RasterXSize) f.write(' UNIT = METER\n') f.write(' OFFSET = %.10g\n' % (hBand.GetOffset())) f.write(' SCALING_FACTOR = %.10g\n' % (hBand.GetScale())) f.write(' SAMPLE_TYPE = %s\n' % (sample_type)) f.write(' SAMPLE_BITS = %d\n' % (sample_bits)) f.write(' SAMPLE_BIT_MASK = %s\n' % (sample_mask)) #f.write('\n') f.write(' BANDS = %d\n' % hDataset.RasterCount) #f.write('\n') f.write(' BAND_STORAGE_TYPE = BAND_SEQUENTIAL\n') if (sample_bits == 32): f.write(' CORE_NULL = 16#FF7FFFFB#\n') f.write(' CORE_LOW_REPR_SATURATION = 16#FF7FFFFC#\n') f.write(' CORE_LOW_INSTR_SATURATION = 16#FF7FFFFD#\n') f.write(' CORE_HIGH_REPR_SATURATION = 16#FF7FFFFF#\n') f.write(' CORE_HIGH_INSTR_SATURATION = 16#FF7FFFFE#\n') elif (sample_bits == 16): f.write(' CORE_NULL = -32768\n') f.write(' CORE_LOW_REPR_SATURATION = -32767\n') f.write(' CORE_LOW_INSTR_SATURATION = -32766\n') f.write(' CORE_HIGH_REPR_SATURATION = 32767\n') f.write(' CORE_HIGH_INSTR_SATURATION = 32768\n') else: #8bit f.write(' CORE_NULL = 0\n') f.write(' CORE_LOW_REPR_SATURATION = 0\n') f.write(' CORE_LOW_INSTR_SATURATION = 0\n') f.write(' CORE_HIGH_REPR_SATURATION = 255\n') f.write(' CORE_HIGH_INSTR_SATURATION = 255\n') f.write('END_OBJECT = IMAGE\n') f.write('END\n') f.close() ######################### #Export out raw image ######################### #Setup the output dataset print('Please wait, writing out raw image: %s' % dst_img) driver = gdal.GetDriverByName('ENVI') output = driver.CreateCopy(dst_img, hDataset, 1) print('Complete. PDS label also created: %s' % dst_lbl) return 0
def main(args = None): global Verbose global CreateOptions global Names global TileWidth global TileHeight global Format global BandType global Driver global Extension global MemDriver global TileIndexFieldName global TileIndexName global CsvDelimiter global CsvFileName global TileIndexDriverTyp global Source_SRS global TargetDir global ResamplingMethod global Levels global PyramidOnly global UseDirForEachRow gdal.AllRegister() if args is None: args = sys.argv argv = gdal.GeneralCmdLineProcessor( args ) if argv is None: return 1 # Parse command line arguments. i = 1 while i < len(argv): arg = argv[i] if arg == '-of': i+=1 Format = argv[i] elif arg == '-ot': i+=1 BandType = gdal.GetDataTypeByName( argv[i] ) if BandType == gdal.GDT_Unknown: print('Unknown GDAL data type: %s' % argv[i]) return 1 elif arg == '-co': i+=1 CreateOptions.append( argv[i] ) elif arg == '-v': Verbose = True elif arg == '-targetDir': i+=1 TargetDir=argv[i] if os.path.exists(TargetDir)==False: print("TargetDir " + TargetDir + " does not exist") return 1 if TargetDir[len(TargetDir)-1:] != os.sep: TargetDir = TargetDir+os.sep elif arg == '-ps': i+=1 TileWidth=int(argv[i]) i+=1 TileHeight=int(argv[i]) elif arg == '-r': i+=1 ResamplingMethodString=argv[i] if ResamplingMethodString=="near": ResamplingMethod=GRA_NearestNeighbour elif ResamplingMethodString=="bilinear": ResamplingMethod=GRA_Bilinear elif ResamplingMethodString=="cubic": ResamplingMethod=GRA_Cubic elif ResamplingMethodString=="cubicspline": ResamplingMethod=GRA_CubicSpline elif ResamplingMethodString=="lanczos": ResamplingMethod=GRA_Lanczos else: print("Unknown resampling method: %s" % ResamplingMethodString) return 1 elif arg == '-levels': i+=1 Levels=int(argv[i]) if Levels<1: print("Invalid number of levels : %d" % Levels) return 1 elif arg == '-s_srs': i+=1 Source_SRS = osr.SpatialReference() if Source_SRS.SetFromUserInput( argv[i] ) != 0: print('invalid -s_srs: ' + argv[i]); return 1; elif arg == "-pyramidOnly": PyramidOnly=True elif arg == '-tileIndex': i+=1 TileIndexName=argv[i] parts=os.path.splitext(TileIndexName) if len(parts[1])==0: TileIndexName+=".shp" elif arg == '-tileIndexField': i+=1 TileIndexFieldName=argv[i] elif arg == '-csv': i+=1 CsvFileName=argv[i] parts=os.path.splitext(CsvFileName) if len(parts[1])==0: CsvFileName+=".csv" elif arg == '-csvDelim': i+=1 CsvDelimiter=argv[i] elif arg == '-useDirForEachRow': UseDirForEachRow=True elif arg[:1] == '-': print('Unrecognised command option: %s' % arg) Usage() return 1 else: Names.append( arg ) i+=1 if len(Names) == 0: print('No input files selected.') Usage() return 1 if (TileWidth==0 or TileHeight==0): print("Invalid tile dimension %d,%d" % (TileWidth,TileHeight)) return 1 if (TargetDir is None): print("Missing Directory for Tiles -targetDir") Usage() return 1 # create level 0 directory if needed if(UseDirForEachRow and PyramidOnly==False) : leveldir=TargetDir+str(0)+os.sep if (os.path.exists(leveldir)==False): os.mkdir(leveldir) if Levels > 0: #prepare Dirs for pyramid startIndx=1 for levelIndx in range (startIndx,Levels+1): leveldir=TargetDir+str(levelIndx)+os.sep if (os.path.exists(leveldir)): continue os.mkdir(leveldir) if (os.path.exists(leveldir)==False): print("Cannot create level dir: %s" % leveldir) return 1 if Verbose : print("Created level dir: %s" % leveldir) Driver = gdal.GetDriverByName(Format) if Driver is None: print('Format driver %s not found, pick a supported driver.' % Format) UsageFormat() return 1 DriverMD = Driver.GetMetadata() Extension=DriverMD.get(DMD_EXTENSION); if 'DCAP_CREATE' not in DriverMD: MemDriver=gdal.GetDriverByName("MEM") tileIndexDS=getTileIndexFromFiles(Names,TileIndexDriverTyp) if tileIndexDS is None: print("Error building tile index") return 1; minfo = mosaic_info(Names[0],tileIndexDS) ti=tile_info(minfo.xsize,minfo.ysize, TileWidth, TileHeight) if Source_SRS is None and len(minfo.projection) > 0 : Source_SRS = osr.SpatialReference() if Source_SRS.SetFromUserInput( minfo.projection ) != 0: print('invalid projection ' + minfo.projection); return 1 if Verbose: minfo.report() ti.report() if PyramidOnly==False: dsCreatedTileIndex = tileImage(minfo,ti) tileIndexDS.Destroy() else: dsCreatedTileIndex=tileIndexDS if Levels>0: buildPyramid(minfo,dsCreatedTileIndex,TileWidth, TileHeight) if Verbose: print("FINISHED") return 0
def main(argv): names = [] out_file = 'out.vrt' ulx = None psize_x = None separate = False # pre_init = None argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 0 # Parse command line arguments. i = 1 while i < len(argv): arg = argv[i] if arg == '-o': i = i + 1 out_file = argv[i] elif arg == '-i': i = i + 1 in_file_list = open(argv[i]) names.extend(in_file_list.read().split()) elif arg == '-separate': separate = True elif arg == '-ul_lr': ulx = float(argv[i + 1]) uly = float(argv[i + 2]) lrx = float(argv[i + 3]) lry = float(argv[i + 4]) i = i + 4 elif arg[:1] == '-': print('Unrecognized command option: ', arg) Usage() return 1 else: names.append(arg) i = i + 1 if not names: print('No input files selected.') Usage() return 1 # Collect information on all the source files. file_infos = names_to_fileinfos(names) if not file_infos: print('Nothing to process, exiting.') return 1 if ulx is None: ulx = file_infos[0].ulx uly = file_infos[0].uly lrx = file_infos[0].lrx lry = file_infos[0].lry for fi in file_infos: ulx = min(ulx, fi.ulx) uly = max(uly, fi.uly) lrx = max(lrx, fi.lrx) lry = min(lry, fi.lry) if psize_x is None: psize_x = file_infos[0].geotransform[1] psize_y = file_infos[0].geotransform[5] projection = file_infos[0].projection for fi in file_infos: if fi.geotransform[1] != psize_x or fi.geotransform[5] != psize_y: print("All files must have the same scale; %s does not" % fi.filename) return 1 if fi.geotransform[2] != 0 or fi.geotransform[4] != 0: print("No file must be rotated; %s is" % fi.filename) return 1 if fi.projection != projection: print("All files must be in the same projection; %s is not" % fi.filename) return 1 geotransform = (ulx, psize_x, 0.0, uly, 0.0, psize_y) xsize = int(((lrx - ulx) / geotransform[1]) + 0.5) ysize = int(((lry - uly) / geotransform[5]) + 0.5) if separate: bands = len(file_infos) else: bands = file_infos[0].bands t_fh = open(out_file, 'w') t_fh.write('<VRTDataset rasterXSize="%i" rasterYSize="%i">\n' % (xsize, ysize)) t_fh.write( '\t<GeoTransform>%24.16f, %24.16f, %24.16f, %24.16f, %24.16f, %24.16f</GeoTransform>\n' % geotransform) if projection: t_fh.write('\t<SRS>%s</SRS>\n' % projection) if separate: band_n = 0 for fi in file_infos: band_n = band_n + 1 if len(fi.band_types) != 2: print('File %s has %d bands. Only first band will be taken ' 'into account' % (fi.filename, len(fi.band_types) - 1)) dataType = gdal.GetDataTypeName(fi.band_types[1]) t_fh.write('\t<VRTRasterBand dataType="%s" band="%i">\n' % (dataType, band_n)) t_fh.write('\t\t<ColorInterp>%s</ColorInterp>\n' % gdal.GetColorInterpretationName(fi.color_interps[1])) fi.write_source(t_fh, geotransform, xsize, ysize, 1) t_fh.write('\t</VRTRasterBand>\n') else: for band in range(1, bands + 1): dataType = gdal.GetDataTypeName(file_infos[0].band_types[band]) t_fh.write('\t<VRTRasterBand dataType="%s" band="%i">\n' % (dataType, band)) if file_infos[0].nodata != [None]: t_fh.write('\t\t<NoDataValue>%f</NoDataValue>\n' % file_infos[0].nodata[band]) t_fh.write('\t\t<ColorInterp>%s</ColorInterp>\n' % gdal.GetColorInterpretationName( file_infos[0].color_interps[band])) ct = file_infos[0].cts[band] if ct is not None: t_fh.write('\t\t<ColorTable>\n') for i in range(ct.GetCount()): t_fh.write( '\t\t\t<Entry c1="%i" c2="%i" c3="%i" c4="%i"/>\n' % ct.GetColorEntry(i)) t_fh.write('\t\t</ColorTable>\n') for fi in file_infos: fi.write_source(t_fh, geotransform, xsize, ysize, band) t_fh.write('\t</VRTRasterBand>\n') t_fh.write('</VRTDataset>\n') return 0
def main(argv=None): bComputeMinMax = False bShowGCPs = True bShowMetadata = True bShowRAT = True bStats = False bApproxStats = True bShowColorTable = True bComputeChecksum = False bReportHistograms = False pszFilename = None papszExtraMDDomains = [] pszProjection = None hTransform = None bShowFileList = True # Must process GDAL_SKIP before GDALAllRegister(), but we can't call # GDALGeneralCmdLineProcessor before it needs the drivers to be registered # for the --format or --formats options # for( i = 1; i < argc; i++ ) # { # if EQUAL(argv[i],"--config") and i + 2 < argc and EQUAL(argv[i + 1], "GDAL_SKIP"): # { # CPLSetConfigOption( argv[i+1], argv[i+2] ); # # i += 2; # } # } # # GDALAllRegister(); if argv is None: argv = sys.argv argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 1 nArgc = len(argv) # -------------------------------------------------------------------- # Parse arguments. # -------------------------------------------------------------------- i = 1 while i < nArgc: if EQUAL(argv[i], "--utility_version"): print("%s is running against GDAL %s" % (argv[0], gdal.VersionInfo("RELEASE_NAME"))) return 0 elif EQUAL(argv[i], "-mm"): bComputeMinMax = True elif EQUAL(argv[i], "-hist"): bReportHistograms = True elif EQUAL(argv[i], "-stats"): bStats = True bApproxStats = False elif EQUAL(argv[i], "-approx_stats"): bStats = True bApproxStats = True elif EQUAL(argv[i], "-checksum"): bComputeChecksum = True elif EQUAL(argv[i], "-nogcp"): bShowGCPs = False elif EQUAL(argv[i], "-nomd"): bShowMetadata = False elif EQUAL(argv[i], "-norat"): bShowRAT = False elif EQUAL(argv[i], "-noct"): bShowColorTable = False elif EQUAL(argv[i], "-mdd") and i < nArgc - 1: i = i + 1 papszExtraMDDomains.append(argv[i]) elif EQUAL(argv[i], "-nofl"): bShowFileList = False elif argv[i][0] == '-': return Usage() elif pszFilename is None: pszFilename = argv[i] else: return Usage() i = i + 1 if pszFilename is None: return Usage() # -------------------------------------------------------------------- # Open dataset. # -------------------------------------------------------------------- hDataset = gdal.Open(pszFilename, gdal.GA_ReadOnly) if hDataset is None: print("gdalinfo failed - unable to open '%s'." % pszFilename) return 1 # -------------------------------------------------------------------- # Report general info. # -------------------------------------------------------------------- hDriver = hDataset.GetDriver() print("Driver: %s/%s" % ( hDriver.ShortName, hDriver.LongName)) papszFileList = hDataset.GetFileList() if papszFileList is None or not papszFileList: print("Files: none associated") else: print("Files: %s" % papszFileList[0]) if bShowFileList: for i in range(1, len(papszFileList)): print(" %s" % papszFileList[i]) print("Size is %d, %d" % (hDataset.RasterXSize, hDataset.RasterYSize)) # -------------------------------------------------------------------- # Report projection. # -------------------------------------------------------------------- pszProjection = hDataset.GetProjectionRef() if pszProjection is not None: hSRS = osr.SpatialReference() if hSRS.ImportFromWkt(pszProjection) == gdal.CE_None: pszPrettyWkt = hSRS.ExportToPrettyWkt(False) print("Coordinate System is:\n%s" % pszPrettyWkt) else: print("Coordinate System is `%s'" % pszProjection) # -------------------------------------------------------------------- # Report Geotransform. # -------------------------------------------------------------------- adfGeoTransform = hDataset.GetGeoTransform(can_return_null=True) if adfGeoTransform is not None: if adfGeoTransform[2] == 0.0 and adfGeoTransform[4] == 0.0: print("Origin = (%.15f,%.15f)" % ( adfGeoTransform[0], adfGeoTransform[3])) print("Pixel Size = (%.15f,%.15f)" % ( adfGeoTransform[1], adfGeoTransform[5])) else: print("GeoTransform =\n" " %.16g, %.16g, %.16g\n" " %.16g, %.16g, %.16g" % ( adfGeoTransform[0], adfGeoTransform[1], adfGeoTransform[2], adfGeoTransform[3], adfGeoTransform[4], adfGeoTransform[5])) # -------------------------------------------------------------------- # Report GCPs. # -------------------------------------------------------------------- if bShowGCPs and hDataset.GetGCPCount() > 0: pszProjection = hDataset.GetGCPProjection() if pszProjection is not None: hSRS = osr.SpatialReference() if hSRS.ImportFromWkt(pszProjection) == gdal.CE_None: pszPrettyWkt = hSRS.ExportToPrettyWkt(False) print("GCP Projection = \n%s" % pszPrettyWkt) else: print("GCP Projection = %s" % pszProjection) gcps = hDataset.GetGCPs() i = 0 for gcp in gcps: print("GCP[%3d]: Id=%s, Info=%s\n" " (%.15g,%.15g) -> (%.15g,%.15g,%.15g)" % ( i, gcp.Id, gcp.Info, gcp.GCPPixel, gcp.GCPLine, gcp.GCPX, gcp.GCPY, gcp.GCPZ)) i = i + 1 # -------------------------------------------------------------------- # Report metadata. # -------------------------------------------------------------------- if bShowMetadata: papszMetadata = hDataset.GetMetadata_List() else: papszMetadata = None if bShowMetadata and papszMetadata: print("Metadata:") for metadata in papszMetadata: print(" %s" % metadata) if bShowMetadata: for extra_domain in papszExtraMDDomains: papszMetadata = hDataset.GetMetadata_List(extra_domain) if papszMetadata: print("Metadata (%s):" % extra_domain) for metadata in papszMetadata: print(" %s" % metadata) # -------------------------------------------------------------------- # Report "IMAGE_STRUCTURE" metadata. # -------------------------------------------------------------------- if bShowMetadata: papszMetadata = hDataset.GetMetadata_List("IMAGE_STRUCTURE") else: papszMetadata = None if bShowMetadata and papszMetadata: print("Image Structure Metadata:") for metadata in papszMetadata: print(" %s" % metadata) # -------------------------------------------------------------------- # Report subdatasets. # -------------------------------------------------------------------- papszMetadata = hDataset.GetMetadata_List("SUBDATASETS") if papszMetadata: print("Subdatasets:") for metadata in papszMetadata: print(" %s" % metadata) # -------------------------------------------------------------------- # Report geolocation. # -------------------------------------------------------------------- if bShowMetadata: papszMetadata = hDataset.GetMetadata_List("GEOLOCATION") else: papszMetadata = None if bShowMetadata and papszMetadata: print("Geolocation:") for metadata in papszMetadata: print(" %s" % metadata) # -------------------------------------------------------------------- # Report RPCs # -------------------------------------------------------------------- if bShowMetadata: papszMetadata = hDataset.GetMetadata_List("RPC") else: papszMetadata = None if bShowMetadata and papszMetadata: print("RPC Metadata:") for metadata in papszMetadata: print(" %s" % metadata) # -------------------------------------------------------------------- # Setup projected to lat/long transform if appropriate. # -------------------------------------------------------------------- if pszProjection: hProj = osr.SpatialReference(pszProjection) if hProj is not None: hLatLong = hProj.CloneGeogCS() if hLatLong is not None: gdal.PushErrorHandler('CPLQuietErrorHandler') hTransform = osr.CoordinateTransformation(hProj, hLatLong) gdal.PopErrorHandler() if gdal.GetLastErrorMsg().find('Unable to load PROJ.4 library') != -1: hTransform = None # -------------------------------------------------------------------- # Report corners. # -------------------------------------------------------------------- print("Corner Coordinates:") GDALInfoReportCorner(hDataset, hTransform, "Upper Left", 0.0, 0.0) GDALInfoReportCorner(hDataset, hTransform, "Lower Left", 0.0, hDataset.RasterYSize) GDALInfoReportCorner(hDataset, hTransform, "Upper Right", hDataset.RasterXSize, 0.0) GDALInfoReportCorner(hDataset, hTransform, "Lower Right", hDataset.RasterXSize, hDataset.RasterYSize) GDALInfoReportCorner(hDataset, hTransform, "Center", hDataset.RasterXSize / 2.0, hDataset.RasterYSize / 2.0) # ==================================================================== # Loop over bands. # ==================================================================== for iBand in range(hDataset.RasterCount): hBand = hDataset.GetRasterBand(iBand + 1) # if( bSample ) # { # float afSample[10000]; # int nCount; # # nCount = GDALGetRandomRasterSample( hBand, 10000, afSample ); # print( "Got %d samples.\n", nCount ); # } (nBlockXSize, nBlockYSize) = hBand.GetBlockSize() print("Band %d Block=%dx%d Type=%s, ColorInterp=%s" % (iBand + 1, nBlockXSize, nBlockYSize, gdal.GetDataTypeName(hBand.DataType), gdal.GetColorInterpretationName( hBand.GetRasterColorInterpretation()))) if hBand.GetDescription() is not None \ and hBand.GetDescription(): print(" Description = %s" % hBand.GetDescription()) dfMin = hBand.GetMinimum() dfMax = hBand.GetMaximum() if dfMin is not None or dfMax is not None or bComputeMinMax: line = " " if dfMin is not None: line = line + ("Min=%.3f " % dfMin) if dfMax is not None: line = line + ("Max=%.3f " % dfMax) if bComputeMinMax: gdal.ErrorReset() adfCMinMax = hBand.ComputeRasterMinMax(False) if gdal.GetLastErrorType() == gdal.CE_None: line = line + (" Computed Min/Max=%.3f,%.3f" % ( adfCMinMax[0], adfCMinMax[1])) print(line) stats = hBand.GetStatistics(bApproxStats, bStats) # Dirty hack to recognize if stats are valid. If invalid, the returned # stddev is negative if stats[3] >= 0.0: print(" Minimum=%.3f, Maximum=%.3f, Mean=%.3f, StdDev=%.3f" % ( stats[0], stats[1], stats[2], stats[3])) if bReportHistograms: hist = hBand.GetDefaultHistogram(force=True, callback=gdal.TermProgress) if hist is not None: dfMin = hist[0] dfMax = hist[1] nBucketCount = hist[2] panHistogram = hist[3] print(" %d buckets from %g to %g:" % ( nBucketCount, dfMin, dfMax)) line = ' ' for bucket in panHistogram: line = line + ("%d " % bucket) print(line) if bComputeChecksum: print(" Checksum=%d" % hBand.Checksum()) dfNoData = hBand.GetNoDataValue() if dfNoData is not None: if dfNoData != dfNoData: print(" NoData Value=nan") else: print(" NoData Value=%.18g" % dfNoData) if hBand.GetOverviewCount() > 0: line = " Overviews: " for iOverview in range(hBand.GetOverviewCount()): if iOverview != 0: line = line + ", " hOverview = hBand.GetOverview(iOverview) if hOverview is not None: line = line + ("%dx%d" % (hOverview.XSize, hOverview.YSize)) pszResampling = \ hOverview.GetMetadataItem("RESAMPLING", "") if pszResampling is not None \ and len(pszResampling) >= 12 \ and EQUAL(pszResampling[0:12], "AVERAGE_BIT2"): line = line + "*" else: line = line + "(null)" print(line) if bComputeChecksum: line = " Overviews checksum: " for iOverview in range(hBand.GetOverviewCount()): if iOverview != 0: line = line + ", " hOverview = hBand.GetOverview(iOverview) if hOverview is not None: line = line + ("%d" % hOverview.Checksum()) else: line = line + "(null)" print(line) if hBand.HasArbitraryOverviews(): print(" Overviews: arbitrary") nMaskFlags = hBand.GetMaskFlags() if (nMaskFlags & (gdal.GMF_NODATA | gdal.GMF_ALL_VALID)) == 0: hMaskBand = hBand.GetMaskBand() line = " Mask Flags: " if (nMaskFlags & gdal.GMF_PER_DATASET) != 0: line = line + "PER_DATASET " if (nMaskFlags & gdal.GMF_ALPHA) != 0: line = line + "ALPHA " if (nMaskFlags & gdal.GMF_NODATA) != 0: line = line + "NODATA " if (nMaskFlags & gdal.GMF_ALL_VALID) != 0: line = line + "ALL_VALID " print(line) if hMaskBand is not None and \ hMaskBand.GetOverviewCount() > 0: line = " Overviews of mask band: " for iOverview in range(hMaskBand.GetOverviewCount()): if iOverview != 0: line = line + ", " hOverview = hMaskBand.GetOverview(iOverview) if hOverview is not None: line = line + ("%d" % hOverview.Checksum()) else: line = line + "(null)" if hBand.GetUnitType(): print(" Unit Type: %s" % hBand.GetUnitType()) papszCategories = hBand.GetRasterCategoryNames() if papszCategories is not None: print(" Categories:") i = 0 for category in papszCategories: print(" %3d: %s" % (i, category)) i = i + 1 scale = hBand.GetScale() if not scale: scale = 1.0 offset = hBand.GetOffset() if not offset: offset = 0.0 if scale != 1.0 or offset != 0.0: print(" Offset: %.15g, Scale:%.15g" % (offset, scale)) if bShowMetadata: papszMetadata = hBand.GetMetadata_List() else: papszMetadata = None if bShowMetadata and papszMetadata: print(" Metadata:") for metadata in papszMetadata: print(" %s" % metadata) if bShowMetadata: papszMetadata = hBand.GetMetadata_List("IMAGE_STRUCTURE") else: papszMetadata = None if bShowMetadata and papszMetadata: print(" Image Structure Metadata:") for metadata in papszMetadata: print(" %s" % metadata) hTable = hBand.GetRasterColorTable() if hBand.GetRasterColorInterpretation() == gdal.GCI_PaletteIndex \ and hTable is not None: print(" Color Table (%s with %d entries)" % ( gdal.GetPaletteInterpretationName( hTable.GetPaletteInterpretation()), hTable.GetCount())) if bShowColorTable: for i in range(hTable.GetCount()): sEntry = hTable.GetColorEntry(i) print(" %3d: %d,%d,%d,%d" % ( i, sEntry[0], sEntry[1], sEntry[2], sEntry[3])) if bShowRAT: pass # hRAT = hBand.GetDefaultRAT() # GDALRATDumpReadable( hRAT, None ); return 0
def main(args=None, g=None): if g is None: g = RetileGlobals() if args is None: args = sys.argv argv = gdal.GeneralCmdLineProcessor(args) if argv is None: return 1 # Parse command line arguments. i = 1 while i < len(argv): arg = argv[i] if arg == '-of' or arg == '-f': i += 1 g.Format = argv[i] elif arg == '-ot': i += 1 g.BandType = gdal.GetDataTypeByName(argv[i]) if g.BandType == gdal.GDT_Unknown: print('Unknown GDAL data type: %s' % argv[i]) return 1 elif arg == '-co': i += 1 g.CreateOptions.append(argv[i]) elif arg == '-v': g.Verbose = True elif arg == '-q': g.Quiet = True elif arg == '-targetDir': i += 1 g.TargetDir = argv[i] if not os.path.exists(g.TargetDir): print("TargetDir " + g.TargetDir + " does not exist") return 1 if g.TargetDir[len(g.TargetDir) - 1:] != os.sep: g.TargetDir = g.TargetDir + os.sep elif arg == '-ps': i += 1 g.TileWidth = int(argv[i]) i += 1 g.TileHeight = int(argv[i]) elif arg == '-overlap': i += 1 g.Overlap = int(argv[i]) elif arg == '-r': i += 1 ResamplingMethodString = argv[i] if ResamplingMethodString == "near": g.ResamplingMethod = gdal.GRA_NearestNeighbour elif ResamplingMethodString == "bilinear": g.ResamplingMethod = gdal.GRA_Bilinear elif ResamplingMethodString == "cubic": g.ResamplingMethod = gdal.GRA_Cubic elif ResamplingMethodString == "cubicspline": g.ResamplingMethod = gdal.GRA_CubicSpline elif ResamplingMethodString == "lanczos": g.ResamplingMethod = gdal.GRA_Lanczos else: print("Unknown resampling method: %s" % ResamplingMethodString) return 1 elif arg == '-levels': i += 1 g.Levels = int(argv[i]) if g.Levels < 1: print("Invalid number of levels : %d" % g.Levels) return 1 elif arg == '-s_srs': i += 1 g.Source_SRS = osr.SpatialReference() if g.Source_SRS.SetFromUserInput(argv[i]) != 0: print('invalid -s_srs: ' + argv[i]) return 1 elif arg == "-pyramidOnly": g.PyramidOnly = True elif arg == '-tileIndex': i += 1 g.TileIndexName = argv[i] parts = os.path.splitext(g.TileIndexName) if not parts[1]: g.TileIndexName += ".shp" elif arg == '-tileIndexField': i += 1 g.TileIndexFieldName = argv[i] elif arg == '-csv': i += 1 g.CsvFileName = argv[i] parts = os.path.splitext(g.CsvFileName) if not parts[1]: g.CsvFileName += ".csv" elif arg == '-csvDelim': i += 1 g.CsvDelimiter = argv[i] elif arg == '-useDirForEachRow': g.UseDirForEachRow = True elif arg == "-resume": g.Resume = True elif arg[:1] == '-': print('Unrecognized command option: %s' % arg) return Usage() else: g.Names.append(arg) i += 1 if not g.Names: print('No input files selected.') return Usage() if (g.TileWidth == 0 or g.TileHeight == 0): print("Invalid tile dimension %d,%d" % (g.TileWidth, g.TileHeight)) return 1 if (g.TileWidth - g.Overlap <= 0 or g.TileHeight - g.Overlap <= 0): print("Overlap too big w.r.t tile height/width") return 1 if g.TargetDir is None: print("Missing Directory for Tiles -targetDir") return Usage() # create level 0 directory if needed if g.UseDirForEachRow and not g.PyramidOnly: leveldir = g.TargetDir + str(0) + os.sep if not os.path.exists(leveldir): os.mkdir(leveldir) if g.Levels > 0: # prepare Dirs for pyramid startIndx = 1 for levelIndx in range(startIndx, g.Levels + 1): leveldir = g.TargetDir + str(levelIndx) + os.sep if os.path.exists(leveldir): continue os.mkdir(leveldir) if not os.path.exists(leveldir): print("Cannot create level dir: %s" % leveldir) return 1 if g.Verbose: print("Created level dir: %s" % leveldir) g.Driver = gdal.GetDriverByName(g.Format) if g.Driver is None: print('Format driver %s not found, pick a supported driver.' % g.Format) return UsageFormat() DriverMD = g.Driver.GetMetadata() g.Extension = DriverMD.get(gdal.DMD_EXTENSION) if 'DCAP_CREATE' not in DriverMD: g.MemDriver = gdal.GetDriverByName("MEM") tileIndexDS = getTileIndexFromFiles(g) if tileIndexDS is None: print("Error building tile index") return 1 minfo = mosaic_info(g.Names[0], tileIndexDS) ti = tile_info(minfo.xsize, minfo.ysize, g.TileWidth, g.TileHeight, g.Overlap) if g.Source_SRS is None and minfo.projection: g.Source_SRS = osr.SpatialReference() if g.Source_SRS.SetFromUserInput(minfo.projection) != 0: print('invalid projection ' + minfo.projection) return 1 if g.Verbose: minfo.report() ti.report() if not g.PyramidOnly: dsCreatedTileIndex = tileImage(g, minfo, ti) tileIndexDS.Destroy() else: dsCreatedTileIndex = tileIndexDS if g.Levels > 0: buildPyramid(g, minfo, dsCreatedTileIndex, g.TileWidth, g.TileHeight, g.Overlap) if g.Verbose: print("FINISHED") return 0
def main(argv): output_format = '-pretty_wkt' authority = None argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 0 # Parse command line arguments. i = 1 while i < len(argv): arg = argv[i] if arg == '-wkt' or arg == '-pretty_wkt' or arg == '-proj4' \ or arg == '-postgis' or arg == '-xml' or arg == '-copy': output_format = arg elif arg == '-authority': i = i + 1 authority = argv[i] elif arg[0] == '-': return Usage() else: return Usage() i = i + 1 # Output BEGIN transaction for PostGIS if output_format == '-postgis': print('BEGIN;') # loop over all codes to generate output if authority: authorities = [authority] elif output_format == '-postgis': authorities = ['EPSG', 'ESRI'] else: authorities = ['EPSG', 'ESRI', 'IGNF'] set_srid = set() for authority in authorities: if authority in ('EPSG', 'ESRI'): set_codes_geographic = set() set_codes_geographic_3d = set() set_codes_projected = set() set_codes_geocentric = set() set_codes_compound = set() set_deprecated = set() for crs_info in osr.GetCRSInfoListFromDatabase(authority): code = int(crs_info.code) if crs_info.type == osr.OSR_CRS_TYPE_COMPOUND: set_codes_compound.add(code) elif crs_info.type == osr.OSR_CRS_TYPE_GEOGRAPHIC_3D: set_codes_geographic_3d.add(code) elif crs_info.type == osr.OSR_CRS_TYPE_GEOGRAPHIC_2D: set_codes_geographic.add(code) elif crs_info.type == osr.OSR_CRS_TYPE_PROJECTED: set_codes_projected.add(code) elif crs_info.type == osr.OSR_CRS_TYPE_GEOCENTRIC: set_codes_geocentric.add(code) if crs_info.deprecated: set_deprecated.add(code) set_codes_geographic = sorted(set_codes_geographic) set_codes_geographic_3d = sorted(set_codes_geographic_3d) set_codes_projected = sorted(set_codes_projected) set_codes_geocentric = sorted(set_codes_geocentric) set_codes_compound = sorted(set_codes_compound) for typestr, set_codes in (('Geographic 2D CRS', set_codes_geographic), ('Projected CRS', set_codes_projected), ('Geocentric CRS', set_codes_geocentric), ('Compound CRS', set_codes_compound), ('Geographic 3D CRS', set_codes_geographic_3d)): if set_codes and output_format == '-postgis': print('-' * 80) print('--- ' + authority + ' ' + typestr) print('-' * 80) for code in set_codes: srs = osr.SpatialReference() srs.SetFromUserInput(authority + ':' + str(code)) deprecated = False if code in set_deprecated: deprecated = True trHandleCode(set_srid, srs, authority, str(code), deprecated, output_format) else: for crs_info in osr.GetCRSInfoListFromDatabase(authority): srs = osr.SpatialReference() srs.SetFromUserInput(authority + ':' + crs_info.code) trHandleCode(set_srid, srs, authority, crs_info.code, crs_info.deprecated, output_format) # Output COMMIT transaction for PostGIS if output_format == '-postgis': print('COMMIT;') print('VACUUM ANALYZE spatial_ref_sys;')
def main(argv=sys.argv): srcwin = None bands = [] filename = None argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 0 # Parse command line arguments. i = 1 while i < len(argv): arg = argv[i] if arg == '-b': i = i + 1 bands.append(int(argv[i])) elif arg == '-srcwin': srcwin = [ int(argv[i + 1]), int(argv[i + 2]), int(argv[i + 3]), int(argv[i + 3]) ] i = i + 4 elif filename is None: filename = argv[i] else: return Usage() i = i + 1 if filename is None: return Usage() # Open source file ds = gdal.Open(filename) if ds is None: print('Unable to open %s' % filename) return 1 # Default values if srcwin is None: srcwin = [0, 0, ds.RasterXSize, ds.RasterYSize] if not bands: bands = list(range(1, (ds.RasterCount + 1))) # Generate checksums for band_num in bands: oBand = ds.GetRasterBand(band_num) result = oBand.Checksum(srcwin[0], srcwin[1], srcwin[2], srcwin[3]) print(result) ds = None
def gdal_edit(argv): argv = gdal.GeneralCmdLineProcessor( argv ) if argv is None: return -1 datasetname = None srs = None ulx = None uly = None lrx = None lry = None nodata = None unsetnodata = False xres = None yres = None unsetgt = False unsetstats = False stats = False approx_stats = False unsetmd = False ro = False molist = [] gcp_list = [] open_options = [] offset = None scale = None colorinterp = {} i = 1 argc = len(argv) while i < argc: if argv[i] == '-ro': ro = True elif argv[i] == '-a_srs' and i < len(argv)-1: srs = argv[i+1] i = i + 1 elif argv[i] == '-a_ullr' and i < len(argv)-4: ulx = float(argv[i+1]) i = i + 1 uly = float(argv[i+1]) i = i + 1 lrx = float(argv[i+1]) i = i + 1 lry = float(argv[i+1]) i = i + 1 elif argv[i] == '-tr' and i < len(argv)-2: xres = float(argv[i+1]) i = i + 1 yres = float(argv[i+1]) i = i + 1 elif argv[i] == '-a_nodata' and i < len(argv)-1: nodata = float(argv[i+1]) i = i + 1 elif argv[i] == '-scale' and i < len(argv)-1: scale = float(argv[i+1]) i = i + 1 elif argv[i] == '-offset' and i < len(argv)-1: offset = float(argv[i+1]) i = i + 1 elif argv[i] == '-mo' and i < len(argv)-1: molist.append(argv[i+1]) i = i + 1 elif argv[i] == '-gcp' and i + 4 < len(argv): pixel = float(argv[i+1]) i = i + 1 line = float(argv[i+1]) i = i + 1 x = float(argv[i+1]) i = i + 1 y = float(argv[i+1]) i = i + 1 if i + 1 < len(argv) and ArgIsNumeric(argv[i+1]): z = float(argv[i+1]) i = i + 1 else: z = 0 gcp = gdal.GCP(x,y,z,pixel,line) gcp_list.append(gcp) elif argv[i] == '-unsetgt' : unsetgt = True elif argv[i] == '-unsetstats': unsetstats = True elif argv[i] == '-approx_stats': stats = True approx_stats = True elif argv[i] == '-stats': stats = True elif argv[i] == '-unsetmd': unsetmd = True elif argv[i] == '-unsetnodata': unsetnodata = True elif argv[i] == '-oo' and i < len(argv)-1: open_options.append(argv[i+1]) i = i + 1 elif argv[i].startswith('-colorinterp_')and i < len(argv)-1: band = int(argv[i][len('-colorinterp_'):]) val = argv[i+1] if val.lower() == 'red': val = gdal.GCI_RedBand elif val.lower() == 'green': val = gdal.GCI_GreenBand elif val.lower() == 'blue': val = gdal.GCI_BlueBand elif val.lower() == 'alpha': val = gdal.GCI_AlphaBand elif val.lower() == 'gray' or val.lower() == 'grey': val = gdal.GCI_GrayIndex elif val.lower() == 'undefined': val = gdal.GCI_Undefined else: sys.stderr.write('Unsupported color interpretation %s.\n' % val + \ 'Only red, green, blue, alpha, gray, undefined are supported.\n' ) return Usage() colorinterp[band] = val i = i + 1 elif argv[i][0] == '-': sys.stderr.write('Unrecognized option : %s\n' % argv[i]) return Usage() elif datasetname is None: datasetname = argv[i] else: sys.stderr.write('Unexpected option : %s\n' % argv[i]) return Usage() i = i + 1 if datasetname is None: return Usage() if (srs is None and lry is None and yres is None and not unsetgt and not unsetstats and not stats and nodata is None and len(molist) == 0 and not unsetmd and len(gcp_list) == 0 and not unsetnodata and len(colorinterp) == 0 and scale is None and offset is None): print('No option specified') print('') return Usage() exclusive_option = 0 if lry is not None: exclusive_option = exclusive_option + 1 if yres is not None: exclusive_option = exclusive_option + 1 if unsetgt: exclusive_option = exclusive_option + 1 if exclusive_option > 1: print('-a_ullr, -tr and -unsetgt options are exclusive.') print('') return Usage() if unsetstats and stats: print('-unsetstats and either -stats or -approx_stats options are exclusive.') print('') return Usage() if unsetnodata and nodata: print('-unsetnodata and -nodata options are exclusive.') print('') return Usage() if open_options is not None: if ro: ds = gdal.OpenEx(datasetname, gdal.OF_RASTER, open_options = open_options) else: ds = gdal.OpenEx(datasetname, gdal.OF_RASTER | gdal.OF_UPDATE, open_options = open_options) # GDAL 1.X compat elif ro: ds = gdal.Open(datasetname) else: ds = gdal.Open(datasetname, gdal.GA_Update) if ds is None: return -1 wkt = None if srs == '' or srs == 'None': ds.SetProjection('') elif srs is not None: sr = osr.SpatialReference() if sr.SetFromUserInput(srs) != 0: print('Failed to process SRS definition: %s' % srs) return -1 wkt = sr.ExportToWkt() if len(gcp_list) == 0: ds.SetProjection(wkt) if lry is not None: gt = [ ulx, (lrx - ulx) / ds.RasterXSize, 0, uly, 0, (lry - uly) / ds.RasterYSize ] ds.SetGeoTransform(gt) if yres is not None: gt = ds.GetGeoTransform() # Doh ! why is gt a tuple and not an array... gt = [ gt[j] for j in range(6) ] gt[1] = xres gt[5] = yres ds.SetGeoTransform(gt) if unsetgt: # For now only the GTiff drivers understands full-zero as a hint # to unset the geotransform if ds.GetDriver().ShortName == 'GTiff': ds.SetGeoTransform([0,0,0,0,0,0]) else: ds.SetGeoTransform([0,1,0,0,0,1]) if len(gcp_list) > 0: if wkt is None: wkt = ds.GetGCPProjection() if wkt is None: wkt = '' ds.SetGCPs(gcp_list, wkt) if nodata is not None: for i in range(ds.RasterCount): ds.GetRasterBand(i+1).SetNoDataValue(nodata) elif unsetnodata: for i in range(ds.RasterCount): ds.GetRasterBand(i+1).DeleteNoDataValue() if scale is not None: for i in range(ds.RasterCount): ds.GetRasterBand(i+1).SetScale(scale) if offset is not None: for i in range(ds.RasterCount): ds.GetRasterBand(i+1).SetOffset(offset) if unsetstats: for i in range(ds.RasterCount): band = ds.GetRasterBand(i+1) for key in band.GetMetadata().keys(): if key.startswith('STATISTICS_'): band.SetMetadataItem(key, None) if stats: for i in range(ds.RasterCount): ds.GetRasterBand(i+1).ComputeStatistics(approx_stats) if len(molist) != 0: if unsetmd: md = {} else: md = ds.GetMetadata() for moitem in molist: equal_pos = moitem.find('=') if equal_pos > 0: md[moitem[0:equal_pos]] = moitem[equal_pos+1:] ds.SetMetadata(md) elif unsetmd: ds.SetMetadata({}) for band in colorinterp: ds.GetRasterBand(band).SetColorInterpretation(colorinterp[band]) ds = band = None return 0
def main(argv): threshold = 2 connectedness = 4 quiet = False src_filename = None dst_filename = None driver_name = None mask = 'default' argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 0 # Parse command line arguments. i = 1 while i < len(argv): arg = argv[i] if arg == '-of' or arg == '-f': i = i + 1 driver_name = argv[i] elif arg == '-4': connectedness = 4 elif arg == '-8': connectedness = 8 elif arg == '-q' or arg == '-quiet': quiet = True elif arg == '-st': i = i + 1 threshold = int(argv[i]) elif arg == '-nomask': mask = 'none' elif arg == '-mask': i = i + 1 mask = argv[i] elif arg == '-mask': i = i + 1 mask = argv[i] elif arg[:2] == '-h': return Usage() elif src_filename is None: src_filename = argv[i] elif dst_filename is None: dst_filename = argv[i] else: return Usage() i = i + 1 if src_filename is None: return Usage() return gdal_sieve(src_filename=src_filename, dst_filename=dst_filename, driver_name=driver_name, mask=mask, threshold=threshold, connectedness=connectedness, quiet=quiet)
def gdal_pansharpen(argv): argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return -1 pan_name = None last_name = None spectral_ds = [] spectral_bands = [] out_name = None bands = [] weights = [] format = 'GTiff' creation_options = [] callback = gdal.TermProgress_nocb resampling = None spat_adjust = None verbose_vrt = False num_threads = None bitdepth = None nodata = None i = 1 argc = len(argv) while i < argc: if argv[i] == '-of' and i < len(argv) - 1: format = argv[i + 1] i = i + 1 elif argv[i] == '-r' and i < len(argv) - 1: resampling = argv[i + 1] i = i + 1 elif argv[i] == '-spat_adjust' and i < len(argv) - 1: spat_adjust = argv[i + 1] i = i + 1 elif argv[i] == '-b' and i < len(argv) - 1: bands.append(int(argv[i + 1])) i = i + 1 elif argv[i] == '-w' and i < len(argv) - 1: weights.append(float(argv[i + 1])) i = i + 1 elif argv[i] == '-co' and i < len(argv) - 1: creation_options.append(argv[i + 1]) i = i + 1 elif argv[i] == '-threads' and i < len(argv) - 1: num_threads = argv[i + 1] i = i + 1 elif argv[i] == '-bitdepth' and i < len(argv) - 1: bitdepth = argv[i + 1] i = i + 1 elif argv[i] == '-nodata' and i < len(argv) - 1: nodata = argv[i + 1] i = i + 1 elif argv[i] == '-q': callback = None elif argv[i] == '-verbose_vrt': verbose_vrt = True elif argv[i][0] == '-': sys.stderr.write('Unrecognized option : %s\n' % argv[i]) return Usage() elif pan_name is None: pan_name = argv[i] pan_ds = gdal.Open(pan_name) if pan_ds is None: return 1 else: if last_name is not None: pos = last_name.find(',band=') if pos > 0: spectral_name = last_name[0:pos] ds = gdal.Open(spectral_name) if ds is None: return 1 band_num = int(last_name[pos + len(',band='):]) band = ds.GetRasterBand(band_num) spectral_ds.append(ds) spectral_bands.append(band) else: spectral_name = last_name ds = gdal.Open(spectral_name) if ds is None: return 1 for j in range(ds.RasterCount): spectral_ds.append(ds) spectral_bands.append(ds.GetRasterBand(j + 1)) last_name = argv[i] i = i + 1 if pan_name is None or len(spectral_bands) == 0: return Usage() out_name = last_name if len(bands) == 0: bands = [j + 1 for j in range(len(spectral_bands))] else: for i in range(len(bands)): if bands[i] < 0 or bands[i] > len(spectral_bands): print('Invalid band number in -b: %d' % bands[i]) return 1 if len(weights) != 0 and len(weights) != len(spectral_bands): print( 'There must be as many -w values specified as input spectral bands' ) return 1 vrt_xml = """<VRTDataset subClass="VRTPansharpenedDataset">\n""" if bands != [j + 1 for j in range(len(spectral_bands))]: for i in range(len(bands)): band = spectral_bands[bands[i] - 1] datatype = gdal.GetDataTypeName(band.DataType) colorname = gdal.GetColorInterpretationName( band.GetColorInterpretation()) vrt_xml += """ <VRTRasterBand dataType="%s" band="%d" subClass="VRTPansharpenedRasterBand"> <ColorInterp>%s</ColorInterp> </VRTRasterBand>\n""" % (datatype, i + 1, colorname) vrt_xml += """ <PansharpeningOptions>\n""" if len(weights) != 0: vrt_xml += """ <AlgorithmOptions>\n""" vrt_xml += """ <Weights>""" for i in range(len(weights)): if i > 0: vrt_xml += "," vrt_xml += "%.16g" % weights[i] vrt_xml += "</Weights>\n" vrt_xml += """ </AlgorithmOptions>\n""" if resampling is not None: vrt_xml += ' <Resampling>%s</Resampling>\n' % resampling if num_threads is not None: vrt_xml += ' <NumThreads>%s</NumThreads>\n' % num_threads if bitdepth is not None: vrt_xml += ' <BitDepth>%s</BitDepth>\n' % bitdepth if nodata is not None: vrt_xml += ' <NoData>%s</NoData>\n' % nodata if spat_adjust is not None: vrt_xml += ' <SpatialExtentAdjustment>%s</SpatialExtentAdjustment>\n' % spat_adjust pan_relative = '0' if format.upper() == 'VRT': if not os.path.isabs(pan_name): pan_relative = '1' pan_name = os.path.relpath(pan_name, os.path.dirname(out_name)) vrt_xml += """ <PanchroBand> <SourceFilename relativeToVRT="%s">%s</SourceFilename> <SourceBand>1</SourceBand> </PanchroBand>\n""" % (pan_relative, pan_name) for i in range(len(spectral_bands)): dstband = '' for j in range(len(bands)): if i + 1 == bands[j]: dstband = ' dstBand="%d"' % (j + 1) break ms_relative = '0' ms_name = spectral_ds[i].GetDescription() if format.upper() == 'VRT': if not os.path.isabs(ms_name): ms_relative = '1' ms_name = os.path.relpath(ms_name, os.path.dirname(out_name)) vrt_xml += """ <SpectralBand%s> <SourceFilename relativeToVRT="%s">%s</SourceFilename> <SourceBand>%d</SourceBand> </SpectralBand>\n""" % (dstband, ms_relative, ms_name, spectral_bands[i].GetBand()) vrt_xml += """ </PansharpeningOptions>\n""" vrt_xml += """</VRTDataset>\n""" if format.upper() == 'VRT': f = gdal.VSIFOpenL(out_name, 'wb') if f is None: print('Cannot create %s' % out_name) return 1 gdal.VSIFWriteL(vrt_xml, 1, len(vrt_xml), f) gdal.VSIFCloseL(f) if verbose_vrt: vrt_ds = gdal.Open(out_name, gdal.GA_Update) vrt_ds.SetMetadata(vrt_ds.GetMetadata()) else: vrt_ds = gdal.Open(out_name) if vrt_ds is None: return 1 return 0 vrt_ds = gdal.Open(vrt_xml) out_ds = gdal.GetDriverByName(format).CreateCopy(out_name, vrt_ds, 0, creation_options, callback=callback) if out_ds is None: return 1 return 0
def main(): global create_csv global fields_descript global fields_csv inRasters = [] rasterPath = None inShapeName = None ext = None nodata = -9999 needTransform = False gdalalloc = False fields_descript = False create_csv = False rasterPaths2 = None quiet = False gdal.AllRegister() formats = gdalInfo().getSupportedRasters() ### print formats args = gdal.GeneralCmdLineProcessor(sys.argv) if args is None or len(args) < 2: usage() # parse command line arguments i = 1 while i < len(args): arg = args[i] if arg == '-r': needTransform = True elif arg == '-g': gdalalloc = True elif arg == '-q': quiet = True elif arg == '-f': fields_descript = True elif arg == '-c': create_csv = True elif arg == '-rl': inRasters.extend(args[i + 1].split(',')) elif arg == '-d': i += 1 rasterPaths = args[i] rasterPaths2 = [] for rasterPath in rasterPaths.split(','): if os.path.exists(rasterPath) == False: print('Directory ' + rasterPath + ' does not exist') if rasterPath[len(rasterPath) - 1:] != os.sep: rasterPath = rasterPath + os.sep rasterPaths2.append(rasterPath) if len(rasterPaths2) == 0: sys.exit(1) elif arg == '-e': i += 1 ext = args[i] elif arg == '-nodata': i += 1 nodata = int(args[i]) elif inShapeName is None: inShapeName = arg elif arg != '-d' and arg != '-rl': inRasters.append(args[i]) i += 1 if not quiet: print('Found GDAL version:', gdalInfo().version(), '\n') if inShapeName is None: print("No point shapefile was specified. Nothing to do.") sys.exit(1) if fields_descript: fields_csv = open(inShapeName.replace('.shp', '_fields.csv'), 'wb') fields_csv.write('RASTER;NEWFIELD;BAND\n') if create_csv: extract_csv = open(inShapeName.replace('.shp', '_extract.csv'), 'wb') #-d is set if rasterPaths2 is not None: if ext is not None: for rasterPaths in rasterPaths2: f = '*.' + ext if f not in formats: print('Raster extension (%s) is not supported' % ext) sys.exit(1) files = glob.glob(rasterPath + f) inRasters.extend(files) else: for rasterPaths in rasterPaths2: for f in formats: # look for supported rasters in directory files = glob.glob(rasterPath + f) inRasters.extend(files) if len(inRasters) == 0: print('No input rasters selected.') usage() # convert filenames to fileinfos fileInfos, bands = fileNamesToFileInfos(inRasters) # try to open source shapefile if int(gdal.VersionInfo()) > 1990000: inShape = ogr.Open(inShapeName, gdal.OF_VECTOR) else: inShape = ogr.Open(inShapeName, 1) if inShape is None: print('Unable to open shapefile', inShapeName) sys.exit(1) inLayer = inShape.GetLayer(0) if fields_descript: layerDefinition = inLayer.GetLayerDefn() for i in range(layerDefinition.GetFieldCount()): fields_csv.write( layerDefinition.GetFieldDefn(i).GetName() + ';' + layerDefinition.GetFieldDefn(i).GetName() + ';1\n') if create_csv: extract_csv.write('FID') featCount = inLayer.GetFeatureCount() layerCRS = inLayer.GetSpatialRef() # add new fields to the shapefile createFields(inLayer, fileInfos) # init progressbar if gdalalloc: max = featCount * len(inRasters) else: max = featCount * bands if not quiet: pb = ProgressBar(max + 1, 65) i = 0 start = time.time() # process points and rasters fi = 0 if create_csv: arExt = np.zeros((featCount, len(fileInfos) + 1)) for f in fileInfos: fi += 1 i += 1 if not quiet: pb.update(i) gt = f.geotransform rasterCRS = f.projection #print("Layer", layerCRS.ExportToWkt()) #print("Raster", rasterCRS.ExportToWkt()) if needTransform: coordTransform = osr.CoordinateTransformation(layerCRS, rasterCRS) if coordTransform is None and needTransform: print('Error while creating coordinate transformation.') sys.exit(1) if not gdalalloc: ds = gdal.Open(f.fileName) if f.bands == 1: shortName = f.fileBaseName[:10] if not gdalalloc: band = ds.ReadAsArray() inLayer.ResetReading() inFeat = inLayer.GetNextFeature() while inFeat is not None: i += 1 if not quiet: pb.update(i) geom = inFeat.GetGeometryRef() x = geom.GetX() y = geom.GetY() #print("BEFORE", x, y) if needTransform: res = coordTransform.TransformPoint(x, y, 0) x = res[0] y = res[1] rX, rY = mapToPixel(x, y, gt) if rX > f.xSize or rY > f.ySize: inFeat = inLayer.GetNextFeature() continue if gdalalloc: value = os.popen( 'gdallocationinfo -valonly -wgs84 %s %s %s' % (f.fileName, x, y)).read() else: value = band[rY, rX] if np.isclose(float(value), f.nodata[0]): value = -9999 if create_csv: arExt[inFeat.GetFID(), 0] = inFeat.GetFID() arExt[inFeat.GetFID(), fi] = value else: inFeat.SetField(shortName, float(value)) if inLayer.SetFeature(inFeat) != 0: print('Failed to update feature.') sys.exit(1) inFeat = inLayer.GetNextFeature() else: shortName = f.fileBaseName[:8] inLayer.ResetReading() inFeat = inLayer.GetNextFeature() while inFeat is not None: i += 1 if not quiet: pb.update(i) geom = inFeat.GetGeometryRef() x = geom.GetX() y = geom.GetY() if needTransform: res = coordTransform.TransformPoint(x, y, 0) x = res[0] y = res[1] rX, rY = mapToPixel(x, y, gt) if rX > f.xSize or rY > f.ySize: inFeat = inLayer.GetNextFeature() continue if gdalalloc: #TODO: check that raster has CRS assigned values = os.popen( 'gdallocationinfo -valonly -wgs84 %s %s %s' % (f.fileName, x, y)).read().split('\n') values = [v.replace('.#IND', '') for v in values] values = [ -9999 if np.isclose(float(v), f.nodata[idx]) else v for idx, v in enumerate(values) ] for b in range(f.bands): if create_csv: arExt[inFeat.GetFID(), 0] = inFeat.GetFID() arExt[inFeat.GetFID(), fi] = float(values[b]) else: inFeat.SetField(shortName + str(b + 1), float(values[b])) if inLayer.SetFeature(inFeat) != 0: print('Failed to update feature.') sys.exit(1) else: for b in range(f.bands): rband = ds.GetRasterBand(b + 1) band = rband.ReadAsArray() value = band[rY, rX] rband = None if create_csv: arExt[inFeat.GetFID(), 0] = inFeat.GetFID() arExt[inFeat.GetFID(), fi] = value else: inFeat.SetField(shortName + str(b + 1), float(value)) if inLayer.SetFeature(inFeat) != 0: print('Failed to update feature.') sys.exit(1) inFeat = inLayer.GetNextFeature() ds = None if create_csv: for r in range(featCount): extract_csv.write('\n') extract_csv.write(str(arExt[r, 0]) + ';') for c in range(1, fi): extract_csv.write(str(arExt[r, c]) + ';') extract_csv.write(str(arExt[r, fi])) if not quiet: pb.done()
def main(argv=None): global verbose, quiet verbose = 0 quiet = 0 names = [] frmt = None out_file = 'out.tif' ulx = None psize_x = None separate = 0 copy_pct = 0 nodata = None a_nodata = None create_options = [] pre_init = [] band_type = None createonly = 0 bTargetAlignedPixels = False start_time = time.time() gdal.AllRegister() if argv is None: argv = sys.argv 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 == '-o': i = i + 1 out_file = argv[i] elif arg == '-v': verbose = 1 elif arg == '-q' or arg == '-quiet': quiet = 1 elif arg == '-createonly': createonly = 1 elif arg == '-separate': separate = 1 elif arg == '-seperate': separate = 1 elif arg == '-pct': copy_pct = 1 elif arg == '-ot': i = i + 1 band_type = gdal.GetDataTypeByName(argv[i]) if band_type == gdal.GDT_Unknown: print('Unknown GDAL data type: %s' % argv[i]) sys.exit(1) elif arg == '-init': i = i + 1 str_pre_init = argv[i].split() for x in str_pre_init: pre_init.append(float(x)) elif arg == '-n': i = i + 1 nodata = float(argv[i]) elif arg == '-a_nodata': i = i + 1 a_nodata = float(argv[i]) elif arg == '-f' or arg == '-of': i = i + 1 frmt = argv[i] elif arg == '-co': i = i + 1 create_options.append(argv[i]) elif arg == '-ps': psize_x = float(argv[i + 1]) psize_y = -1 * abs(float(argv[i + 2])) i = i + 2 elif arg == '-tap': bTargetAlignedPixels = True elif arg == '-ul_lr': ulx = float(argv[i + 1]) uly = float(argv[i + 2]) lrx = float(argv[i + 3]) lry = float(argv[i + 4]) i = i + 4 elif arg[:1] == '-': print('Unrecognized command option: %s' % arg) Usage() sys.exit(1) else: names.append(arg) i = i + 1 if not names: print('No input files selected.') Usage() sys.exit(1) if frmt is None: frmt = GetOutputDriverFor(out_file) Driver = gdal.GetDriverByName(frmt) if Driver is None: print('Format driver %s not found, pick a supported driver.' % frmt) sys.exit(1) DriverMD = Driver.GetMetadata() if 'DCAP_CREATE' not in DriverMD: print( 'Format driver %s does not support creation and piecewise writing.\nPlease select a format that does, such as GTiff (the default) or HFA (Erdas Imagine).' % frmt) sys.exit(1) # Collect information on all the source files. file_infos = names_to_fileinfos(names) if ulx is None: ulx = file_infos[0].ulx uly = file_infos[0].uly lrx = file_infos[0].lrx lry = file_infos[0].lry for fi in file_infos: ulx = min(ulx, fi.ulx) uly = max(uly, fi.uly) lrx = max(lrx, fi.lrx) lry = min(lry, fi.lry) if psize_x is None: psize_x = file_infos[0].geotransform[1] psize_y = file_infos[0].geotransform[5] if band_type is None: band_type = file_infos[0].band_type # Try opening as an existing file. gdal.PushErrorHandler('CPLQuietErrorHandler') t_fh = gdal.Open(out_file, gdal.GA_Update) gdal.PopErrorHandler() # Create output file if it does not already exist. if t_fh is None: if bTargetAlignedPixels: ulx = math.floor(ulx / psize_x) * psize_x lrx = math.ceil(lrx / psize_x) * psize_x lry = math.floor(lry / -psize_y) * -psize_y uly = math.ceil(uly / -psize_y) * -psize_y geotransform = [ulx, psize_x, 0, uly, 0, psize_y] xsize = int((lrx - ulx) / geotransform[1] + 0.5) ysize = int((lry - uly) / geotransform[5] + 0.5) if separate != 0: bands = 0 for fi in file_infos: bands = bands + fi.bands else: bands = file_infos[0].bands t_fh = Driver.Create(out_file, xsize, ysize, bands, band_type, create_options) if t_fh is None: print('Creation failed, terminating gdal_merge.') sys.exit(1) t_fh.SetGeoTransform(geotransform) t_fh.SetProjection(file_infos[0].projection) if copy_pct: t_fh.GetRasterBand(1).SetRasterColorTable(file_infos[0].ct) else: if separate != 0: bands = 0 for fi in file_infos: bands = bands + fi.bands if t_fh.RasterCount < bands: print( 'Existing output file has less bands than the input files. You should delete it before. Terminating gdal_merge.' ) sys.exit(1) else: bands = min(file_infos[0].bands, t_fh.RasterCount) # Do we need to set nodata value ? if a_nodata is not None: for i in range(t_fh.RasterCount): t_fh.GetRasterBand(i + 1).SetNoDataValue(a_nodata) # Do we need to pre-initialize the whole mosaic file to some value? if pre_init is not None: if t_fh.RasterCount <= len(pre_init): for i in range(t_fh.RasterCount): t_fh.GetRasterBand(i + 1).Fill(pre_init[i]) elif len(pre_init) == 1: for i in range(t_fh.RasterCount): t_fh.GetRasterBand(i + 1).Fill(pre_init[0]) # Copy data from source files into output file. t_band = 1 if quiet == 0 and verbose == 0: progress(0.0) fi_processed = 0 for fi in file_infos: if createonly != 0: continue if verbose != 0: print("") print( "Processing file %5d of %5d, %6.3f%% completed in %d minutes." % (fi_processed + 1, len(file_infos), fi_processed * 100.0 / len(file_infos), int(round( (time.time() - start_time) / 60.0)))) fi.report() if separate == 0: for band in range(1, bands + 1): fi.copy_into(t_fh, band, band, nodata) else: for band in range(1, fi.bands + 1): fi.copy_into(t_fh, band, t_band, nodata) t_band = t_band + 1 fi_processed = fi_processed + 1 if quiet == 0 and verbose == 0: progress(fi_processed / float(len(file_infos))) # Force file to be closed. t_fh = None
def main(argv=sys.argv): driver_name = None creation_options = [] alg_options = [] src_filename = None src_band_n = 1 dst_filename = None dst_band_n = 1 creation_type = 'Float32' quiet = False argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 0 # Parse command line arguments. i = 1 while i < len(argv): arg = argv[i] if arg == '-of' or arg == '-f': i = i + 1 driver_name = 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 alg_options.append('MAXDIST=' + argv[i]) elif arg == '-values': i = i + 1 alg_options.append('VALUES=' + argv[i]) elif arg == '-distunits': i = i + 1 alg_options.append('DISTUNITS=' + argv[i]) elif arg == '-nodata': i = i + 1 alg_options.append('NODATA=' + argv[i]) elif arg == '-use_input_nodata': i = i + 1 alg_options.append('USE_INPUT_NODATA=' + argv[i]) elif arg == '-fixed-buf-val': i = i + 1 alg_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 = True elif src_filename is None: src_filename = argv[i] elif dst_filename is None: dst_filename = argv[i] else: return Usage() i = i + 1 if src_filename is None or dst_filename is None: return Usage() return gdal_proximity(src_filename=src_filename, src_band_n=src_band_n, dst_filename=dst_filename, dst_band_n=dst_band_n, driver_name=driver_name, creation_type=creation_type, creation_options=creation_options, alg_options=alg_options, quiet=quiet)
sys.exit(1) ############################################################################# # Argument processing. infile = None outfile = None layer_list = [] relative = "0" schema = 0 feature_count = 0 extent = 0 openoptions = [] argv = gdal.GeneralCmdLineProcessor(sys.argv) if argv is None: sys.exit(0) i = 1 while i < len(argv): arg = argv[i] if arg == '-relative': relative = "1" elif arg == '-schema': schema = 1 elif arg == '-feature_count': feature_count = 1
def main(argv): infile = None outfile = None layer_list = [] relative = "0" schema = 0 feature_count = 0 extent = 0 openoptions = [] argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 0 i = 1 while i < len(argv): arg = argv[i] if arg == '-relative': relative = "1" elif arg == '-schema': schema = 1 elif arg == '-feature_count': feature_count = 1 elif arg == '-extent': extent = 1 elif arg == '-oo': i += 1 openoptions.append(argv[i]) elif arg[0] == '-': return Usage() elif infile is None: infile = arg elif outfile is None: outfile = arg else: layer_list.append(arg) i = i + 1 if outfile is None: return Usage() if schema and feature_count: sys.stderr.write('Ignoring -feature_count when used with -schema.\n') feature_count = 0 if schema and extent: sys.stderr.write('Ignoring -extent when used with -schema.\n') extent = 0 ############################################################################# # Open the datasource to read. src_ds = gdal.OpenEx(infile, gdal.OF_VECTOR, open_options=openoptions) if schema: infile = '@dummy@' if not layer_list: for lyr_idx in range(src_ds.GetLayerCount()): layer_list.append( src_ds.GetLayer(lyr_idx).GetLayerDefn().GetName()) ############################################################################# # Start the VRT file. vrt = '<OGRVRTDataSource>\n' ############################################################################# # Metadata mdd_list = src_ds.GetMetadataDomainList() if mdd_list is not None: for domain in mdd_list: if domain == '': vrt += ' <Metadata>\n' elif len(domain) > 4 and domain[0:4] == 'xml:': vrt += ' <Metadata domain="%s" format="xml">\n' % Esc(domain) else: vrt += ' <Metadata domain="%s">\n' % Esc(domain) if len(domain) > 4 and domain[0:4] == 'xml:': vrt += src_ds.GetMetadata_List(domain)[0] else: md = src_ds.GetMetadata(domain) for key in md: vrt += ' <MDI key="%s">%s</MDI>\n' % (Esc(key), Esc(md[key])) vrt += ' </Metadata>\n' ############################################################################# # Process each source layer. for name in layer_list: layer = src_ds.GetLayerByName(name) layerdef = layer.GetLayerDefn() vrt += ' <OGRVRTLayer name="%s">\n' % Esc(name) mdd_list = layer.GetMetadataDomainList() if mdd_list is not None: for domain in mdd_list: if domain == '': vrt += ' <Metadata>\n' elif len(domain) > 4 and domain[0:4] == 'xml:': vrt += ' <Metadata domain="%s" format="xml">\n' % Esc( domain) else: vrt += ' <Metadata domain="%s">\n' % Esc(domain) if len(domain) > 4 and domain[0:4] == 'xml:': vrt += layer.GetMetadata_List(domain)[0] else: md = layer.GetMetadata(domain) for key in md: vrt += ' <MDI key="%s">%s</MDI>\n' % ( Esc(key), Esc(md[key])) vrt += ' </Metadata>\n' if not os.path.isabs(outfile) and not os.path.isabs(infile) and \ os.path.dirname(outfile) == '' and os.path.dirname(infile) == '': relative = 1 vrt += ' <SrcDataSource relativeToVRT="%s" shared="%d">%s</SrcDataSource>\n' \ % (relative, not schema, Esc(infile)) if openoptions: vrt += ' <OpenOptions>\n' for option in openoptions: (key, value) = option.split('=') vrt += ' <OOI key="%s">%s</OOI>\n' % (Esc(key), Esc(value)) vrt += ' </OpenOptions>\n' if schema: vrt += ' <SrcLayer>@dummy@</SrcLayer>\n' else: vrt += ' <SrcLayer>%s</SrcLayer>\n' % Esc(name) # Historic format for mono-geometry layers if layerdef.GetGeomFieldCount() == 0: vrt += ' <GeometryType>wkbNone</GeometryType>\n' elif layerdef.GetGeomFieldCount() == 1 and \ layerdef.GetGeomFieldDefn(0).IsNullable(): vrt += ' <GeometryType>%s</GeometryType>\n' \ % GeomType2Name(layerdef.GetGeomType()) srs = layer.GetSpatialRef() if srs is not None: vrt += ' <LayerSRS>%s</LayerSRS>\n' \ % (Esc(srs.ExportToWkt())) if extent: (xmin, xmax, ymin, ymax) = layer.GetExtent() vrt += ' <ExtentXMin>%.15g</ExtentXMin>\n' % xmin vrt += ' <ExtentYMin>%.15g</ExtentYMin>\n' % ymin vrt += ' <ExtentXMax>%.15g</ExtentXMax>\n' % xmax vrt += ' <ExtentYMax>%.15g</ExtentYMax>\n' % ymax # New format for multi-geometry field support else: for fld_index in range(layerdef.GetGeomFieldCount()): src_fd = layerdef.GetGeomFieldDefn(fld_index) vrt += ' <GeometryField name="%s"' % src_fd.GetName() if src_fd.IsNullable() == 0: vrt += ' nullable="false"' vrt += '>\n' vrt += ' <GeometryType>%s</GeometryType>\n' \ % GeomType2Name(src_fd.GetType()) srs = src_fd.GetSpatialRef() if srs is not None: vrt += ' <SRS>%s</SRS>\n' \ % (Esc(srs.ExportToWkt())) if extent: (xmin, xmax, ymin, ymax) = layer.GetExtent(geom_field=fld_index) vrt += ' <ExtentXMin>%.15g</ExtentXMin>\n' % xmin vrt += ' <ExtentYMin>%.15g</ExtentYMin>\n' % ymin vrt += ' <ExtentXMax>%.15g</ExtentXMax>\n' % xmax vrt += ' <ExtentYMax>%.15g</ExtentYMax>\n' % ymax vrt += ' </GeometryField>\n' # Process all the fields. for fld_index in range(layerdef.GetFieldCount()): src_fd = layerdef.GetFieldDefn(fld_index) if src_fd.GetType() == ogr.OFTInteger: typ = 'Integer' elif src_fd.GetType() == ogr.OFTInteger64: typ = 'Integer64' elif src_fd.GetType() == ogr.OFTString: typ = 'String' elif src_fd.GetType() == ogr.OFTReal: typ = 'Real' elif src_fd.GetType() == ogr.OFTStringList: typ = 'StringList' elif src_fd.GetType() == ogr.OFTIntegerList: typ = 'IntegerList' elif src_fd.GetType() == ogr.OFTInteger64List: typ = 'Integer64List' elif src_fd.GetType() == ogr.OFTRealList: typ = 'RealList' elif src_fd.GetType() == ogr.OFTBinary: typ = 'Binary' elif src_fd.GetType() == ogr.OFTDate: typ = 'Date' elif src_fd.GetType() == ogr.OFTTime: typ = 'Time' elif src_fd.GetType() == ogr.OFTDateTime: typ = 'DateTime' else: typ = 'String' vrt += ' <Field name="%s" type="%s"' \ % (Esc(src_fd.GetName()), typ) if src_fd.GetSubType() != ogr.OFSTNone: vrt += ' subtype="%s"' % ogr.GetFieldSubTypeName( src_fd.GetSubType()) if not schema: vrt += ' src="%s"' % Esc(src_fd.GetName()) if src_fd.GetWidth() > 0: vrt += ' width="%d"' % src_fd.GetWidth() if src_fd.GetPrecision() > 0: vrt += ' precision="%d"' % src_fd.GetPrecision() if src_fd.IsNullable() == 0: vrt += ' nullable="false"' try: if src_fd.IsUnique(): vrt += ' unique="true"' except AttributeError: # if run with GDAL < 3.2 pass vrt += '/>\n' if feature_count: vrt += ' <FeatureCount>%d</FeatureCount>\n' % layer.GetFeatureCount( ) vrt += ' </OGRVRTLayer>\n' vrt += '</OGRVRTDataSource>\n' ############################################################################# # Write vrt open(outfile, 'w').write(vrt) return 0