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 len(papszFileList) == 0: 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 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. */ #/* -------------------------------------------------------------------- */ 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 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: pass #hRAT = hBand.GetDefaultRAT() #GDALRATDumpReadable( hRAT, None ); return 0
def get_bands_by_raster(self, band_count: int, raster_ds) -> list: """ 获取波段信息(bands节点) :param band_count: :param raster_ds: :return: """ band_list = [] for i_band in range(band_count): band = raster_ds.GetRasterBand(i_band + 1) json_band = CJson() (x_block_size, y_block_size) = band.GetBlockSize() block = CJson() block.set_value_of_name('width', x_block_size) block.set_value_of_name('height', y_block_size) json_band.set_value_of_name('block', block.json_obj) band_type = gdal.GetDataTypeName(band.DataType) json_band.set_value_of_name('type', band_type) color_interp = gdal.GetColorInterpretationName(band.GetRasterColorInterpretation()) json_band.set_value_of_name('color_interp', color_interp) description = band.GetDescription() if description is not None and len(description) > 0: json_band.set_value_of_name('description', description) b_min = band.GetMinimum() b_max = band.GetMaximum() if b_max is not None or b_min is not None: (b_min, b_max) = band.ComputeRasterMinMax(True) json_band.set_value_of_name('min', b_min) json_band.set_value_of_name('max', b_max) no_data = band.GetNoDataValue() if no_data is not None: if math.isnan(no_data): json_band.set_value_of_name('has_no_data_value', False) else: json_band.set_value_of_name('has_no_data_value', True) json_band.set_value_of_name('no_data_value', no_data) overviews = band.GetOverviewCount() if overviews > 0: band_overviews = [] for i_overview in range(overviews): overview = band.GetOverview(i_overview) if overview is not None: json_overview = CJson() json_overview_size = CJson() json_overview_size.set_value_of_name('width', overview.XSize) json_overview_size.set_value_of_name('height', overview.YSize) json_overview.set_value_of_name('size', json_overview_size.json_obj) resampling = overview.GetMetadataItem('RESAMPLING') if resampling is not None and resampling == 'AVERAGE_BIT2': json_overview.set_value_of_name('resampling', '*') band_overviews.append(json_overview.json_obj) json_band.set_value_of_name('overviews', band_overviews) if band.HasArbitraryOverviews(): json_band.set_value_of_name('has_arbitrary_overview', True) json_mask = CJson() json_mask.set_value_of_name('valid', True) mask_flags = band.GetMaskFlags() if mask_flags: mask_band = band.GetMaskBand() if mask_band is not None and mask_band.GetOverviewCount() > 0: mask_overviews = [] for i_overview in range(mask_band.GetOverviewCount()): mask_overview = mask_band.GetOverview(i_overview) if mask_overview is not None: json_mask_overview_size = CJson() json_mask_overview_size.set_value_of_name('width', mask_overview.XSize) json_mask_overview_size.set_value_of_name('height', mask_overview.YSize) mask_overviews.append(json_mask_overview_size.json_obj) json_mask.set_value_of_name('overviews', mask_overviews) json_band.set_value_of_name('mask', json_mask.json_obj) unit = band.GetUnitType() if len(unit) > 0: band_unit = CJson() band_unit.set_value_of_name('type', unit) json_band.set_value_of_name('unit', band_unit.json_obj) category = band.GetRasterCategoryNames() if category is not None: categories = [] for i in category: if category[i] is not None: value = category[i] categories.append(value) json_band.set_value_of_name('categories', categories) scale = band.GetScale() offset = band.GetOffset() if scale != 1.0 or offset != 0: json_band.set_value_of_name('scale', scale) json_band.set_value_of_name('offset', offset) band_metadata = band.GetMetadata() if band_metadata is not None: metadata = [] for i in band_metadata: value = band_metadata[i] metadata.append(value) json_band.set_value_of_name('metadata', metadata) band_image_metadata = band.GetMetadata('IMAGE_STRUCTURE') if band_image_metadata is not None: image_metadata = [] for i in band_image_metadata: value = band_image_metadata[i] image_metadata.append(value) json_band.set_value_of_name('image_structure_metadata', image_metadata) color_table = band.GetRasterColorTable() if color_interp == 'Palette' and color_table is not None: json_color_table = CJson() palette_interpretation = gdal.GetPaletteInterpretationName(color_table.GetPaletteInterpretation()) entry_count = color_table.GetCount() json_color_table.set_value_of_name('palette_interpretation_name', palette_interpretation) json_color_table.set_value_of_name('entry_count', entry_count) color_entry = [] for i in range(entry_count): entry = color_table.GetColorEntry(i) # entry_RGB = color_table.GetColorEntryAsRGB(i, entry) 有必要吗?这句可以删掉? json_color_entry = CJson() json_color_entry.set_value_of_name('color1', entry[0]) json_color_entry.set_value_of_name('color2', entry[1]) json_color_entry.set_value_of_name('color3', entry[2]) json_color_entry.set_value_of_name('color4', entry[3]) color_entry.append(json_color_entry.json_obj) json_color_table.set_value_of_name('entrys', color_entry) json_band.set_value_of_name('color_table', json_color_table.json_obj) band_list.append(json_band.json_obj) band = None return band_list
def main(argv=None): bComputeMinMax = False bSample = False bShowGCPs = True bShowMetadata = False bShowRAT = False debug = False attach = False bStats = False bApproxStats = True bShowColorTable = True bComputeChecksum = False bReportHistograms = False pszFilename = None papszExtraMDDomains = [] pszProjection = None hTransform = None bShowFileList = True dst_cub = None dst_lbl = None dst_hst = None bands = 1 centLat = 0 centLon = 0 centerLon = False TMscale = 1.0 UpperLeftCornerX = 0 UpperLeftCornerY = 0 falseEast = 0 falseNorth = 0 bMakeImage = True force360 = False base = None multiplier = None #/* 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], "-attach"): attach = True elif EQUAL(argv[i], "-force360"): force360 = True elif EQUAL(argv[i], "-centerLon"): i = i + 1 centerLon = float(argv[i]) 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 EQUAL(argv[i], "-noimage"): bMakeImage = False elif EQUAL(argv[i], "-base"): i = i + 1 base = float(argv[i]) elif EQUAL(argv[i], "-multiplier"): i = i + 1 multiplier = float(argv[i]) elif argv[i][0] == '-': return Usage(argv[0]) elif pszFilename is None: pszFilename = argv[i] elif dst_cub is None: dst_cub = argv[i] else: return Usage(argv[0]) i = i + 1 if pszFilename is None: return Usage(argv[0]) if dst_cub 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_cub is not None: dst_lbl = dst_cub.replace("CUB", "LBL") dst_lbl = dst_lbl.replace("cub", "lbl") dst_hst = dst_cub.replace("CUB", "History.IsisCube") dst_hst = dst_hst.replace("cub", "History.IsisCube") dst_hdr = dst_cub.replace("CUB", "hdr") dst_hdr = dst_hdr.replace("cub", "hdr") dst_aux = dst_cub.replace("CUB", "cub.aux.xml") dst_aux = dst_aux.replace("cub", "cub.aux.xml") if attach: attach_cub = dst_cub dst_cub = "XXX" + dst_cub dst_lbl = "XXX" + dst_lbl dst_hst = "XXX" + dst_hst dst_hdr = "XXX" + dst_hdr dst_aux = "XXX" + dst_aux if (EQUAL(dst_lbl, dst_cub)): print( 'Extension must be .CUB or .cub - unable to run using filename: %s' % pszFilename) sys.exit(1) else: f = open(dst_lbl, 'wt') f_hst = open(dst_hst, 'wt') # else: # f = sys.stdout # dst_cub = "out.cub" #/* -------------------------------------------------------------------- */ #/* 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) if debug: print("Coordinate System is:\n%s" % pszPrettyWkt) else: if debug: print("Coordinate System is `%s'" % pszProjection) 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) target = target.replace("D_", "").replace("_2000", "").replace("GCS_", "") semiMajor = hSRS.GetSemiMajor() semiMinor = hSRS.GetSemiMinor() if (pszProjection[0:6] == "GEOGCS"): mapProjection = "SimpleCylindrical" centLon = hSRS.GetProjParm('central_meridian') if (pszProjection[0:6] == "PROJCS"): mapProjection = hSRS.GetAttrValue("PROJECTION", 0) if EQUAL(mapProjection, "Sinusoidal"): centLon = hSRS.GetProjParm('central_meridian') if EQUAL(mapProjection, "Equirectangular"): centLat = hSRS.GetProjParm('standard_parallel_1') centLon = hSRS.GetProjParm('central_meridian') if EQUAL(mapProjection, "Transverse_Mercator"): mapProjection = "TransverseMercator" centLat = hSRS.GetProjParm('standard_parallel_1') centLon = hSRS.GetProjParm('central_meridian') TMscale = hSRS.GetProjParm('scale_factor') #Need to research when TM actually applies false values falseEast = hSRS.GetProjParm('false_easting') falseNorth = hSRS.GetProjParm('false_northing') if EQUAL(mapProjection, "Orthographic"): centLat = hSRS.GetProjParm('standard_parallel_1') centLon = hSRS.GetProjParm('central_meridian') if EQUAL(mapProjection, "Mercator_1SP"): mapProjection = "Mercator" centLat = hSRS.GetProjParm('standard_parallel_1') centLon = hSRS.GetProjParm('central_meridian') if EQUAL(mapProjection, "Mercator"): centLat = hSRS.GetProjParm('standard_parallel_1') centLon = hSRS.GetProjParm('central_meridian') if EQUAL(mapProjection, "Polar_Stereographic"): mapProjection = "PolarStereographic" centLat = hSRS.GetProjParm('latitude_of_origin') centLon = hSRS.GetProjParm('central_meridian') if EQUAL(mapProjection, "Stereographic_South_Pole"): mapProjection = "PolarStereographic" centLat = hSRS.GetProjParm('latitude_of_origin') centLon = hSRS.GetProjParm('central_meridian') if EQUAL(mapProjection, "Stereographic_North_Pole"): mapProjection = "PolarStereographic" centLat = hSRS.GetProjParm('latitude_of_origin') centLon = hSRS.GetProjParm('central_meridian') if debug: print("Coordinate System is:\n%s" % pszPrettyWkt) else: print("Warning - Currently we can't parse this type of projection") print("Coordinate System is `%s'" % pszProjection) target = "n/a" #sys.exit(1) else: print("Warning - No Coordinate System defined:\n") target = "n/a" #sys.exit(1) #/* -------------------------------------------------------------------- */ #/* Report Geotransform. */ #/* -------------------------------------------------------------------- */ adfGeoTransform = hDataset.GetGeoTransform(can_return_null=True) if adfGeoTransform is not None: UpperLeftCornerX = adfGeoTransform[0] - falseEast UpperLeftCornerY = adfGeoTransform[3] - falseNorth 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] )) #Using a very simple method to calculate cellsize. #Warning: might not always be good. if (pszProjection[0:6] == "GEOGCS"): #convert degrees/pixel to m/pixel mapres = 1 / adfGeoTransform[1] mres = adfGeoTransform[1] * (semiMajor * math.pi / 180.0) else: #convert m/pixel to pixel/degree mapres = 1 / (adfGeoTransform[1] / (semiMajor * math.pi / 180.0)) mres = adfGeoTransform[1] #/* -------------------------------------------------------------------- */ #/* 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 ) if (centerLon): centLon = centerLon #Calculate Simple Cylindrical X,Y in meters from bounds if not projected. #Needs testing. if (pszProjection[0:6] == "GEOGCS"): #note that: mres = adfGeoTransform[1] * (semiMajor * math.pi / 180.0) UpperLeftCornerX = semiMajor * (ulx - centLon) * math.pi / 180.0 UpperLeftCornerY = semiMajor * uly * math.pi / 180.0 #/* ==================================================================== */ #/* 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 ); #/***************************************************************************/ #/* WriteISISlabel() */ #/***************************************************************************/ #def WriteISISLabel(outFile, DataSetID, pszFilename, sampleBits, lines, samples): #Currently just procedural programming. Gets the job done... # instrList = pszFilename.split("_") hBand = hDataset.GetRasterBand(1) #get the datatype print gdal.GetDataTypeName(hBand.DataType) if EQUAL(gdal.GetDataTypeName(hBand.DataType), "Float32"): sample_bits = 32 sample_type = "Real" sample_mask = "2#11111111111111111111111111111111#" elif EQUAL(gdal.GetDataTypeName(hBand.DataType), "Float64"): sample_bits = 32 sample_type = "Real" sample_mask = "2#11111111111111111111111111111111#" elif EQUAL(gdal.GetDataTypeName(hBand.DataType), "INT16"): sample_bits = 16 sample_type = "SignedWord" sample_mask = "2#1111111111111111#" elif EQUAL(gdal.GetDataTypeName(hBand.DataType), "UINT16"): sample_bits = 16 sample_type = "UsignedWord" sample_mask = "2#1111111111111111#" elif EQUAL(gdal.GetDataTypeName(hBand.DataType), "Byte"): sample_bits = 8 sample_type = "UnsignedByte" sample_mask = "2#11111111#" else: print( " %s: Not supported pixel type. Please convert to 8, 16 Int, or 32 Float" % gdal.GetDataTypeName(hBand.DataType)) sys.exit(1) f.write('Object = IsisCube\n') f.write(' Object = Core\n') f.write(' StartByte = 1\n') #f.write('/* The source image data definition. */\n') f.write(' ^Core = %s\n' % (dst_cub)) f.write(' Format = BandSequential\n') f.write('\n') f.write(' Group = Dimensions\n') f.write(' Samples = %d\n' % (hDataset.RasterXSize)) f.write(' Lines = %d\n' % hDataset.RasterYSize) f.write(' Bands = %d\n' % hDataset.RasterCount) f.write(' End_Group\n') f.write('\n') f.write(' Group = Pixels\n') f.write(' Type = %s\n' % (sample_type)) f.write(' ByteOrder = Lsb\n') if base is None: f.write(' Base = %.10g\n' % (hBand.GetOffset())) if EQUAL(sample_type, "REAL"): if (hBand.GetOffset() <> 0): print( "Warning: a none 0 'base' was set but input is 32bit Float. ISIS will not use this value when type is REAL. Please use 'fx' to apply this base value: %.10g" % (hBand.GetOffset())) else: f.write(' Base = %.10g\n' % base) if EQUAL(sample_type, "REAL"): print( "Warning: '-base' was set but input is 32bit Float. ISIS will not use this value when type is REAL. Please use 'fx' to apply this base value." ) if multiplier is None: f.write(' Multiplier = %.10g\n' % (hBand.GetScale())) if EQUAL(sample_type, "REAL"): if (hBand.GetScale() <> 1): print( "Warning: a none 1 'multiplier' was set but input is 32bit Float. ISIS will not use this value when type is REAL. Please use 'fx' to apply this multiplier value: %.10g" % (hBand.GetScale())) else: f.write(' Multiplier = %.10g\n' % multiplier) if EQUAL(sample_type, "REAL"): print( "Warning: '-multiplier' was set but input is 32bit Float. ISIS will not use this value when type is REAL. Please use 'fx' to apply this multiplier value." ) f.write(' End_Group\n') f.write(' End_Object\n') f.write('\n') f.write(' Group = Archive\n') f.write(' DataSetId = %s\n' % pszFilename.split(".")[0]) f.write(' ProducerInstitutionName = \"Astrogeology Science Center\"\n') f.write(' ProducerId = Astrogeology\n') f.write(' ProducerFullName = USGS\n') if "_v" in pszFilename: f.write(' ProductId = %s\n' % instrList[-1].split(".")[0].upper()) else: f.write(' ProductId = n/a\n') f.write(' ProductVersionId = n/a\n') f.write(' InstrumentHostName = n/a\n') f.write(' InstrumentName = n/a\n') f.write(' InstrumentId = n/a\n') f.write(' TargetName = %s\n' % target) f.write(' MissionPhaseName = n/a\n') f.write(' End_Group\n') f.write('\n') if target <> "n/a": f.write(' Group = Mapping\n') f.write(' ProjectionName = %s\n' % mapProjection) if ((centLon < 0) and force360): centLon = centLon + 360 f.write(' CenterLongitude = %.5f\n' % centLon) f.write(' CenterLatitude = %.5f\n' % centLat) if EQUAL(mapProjection, "TransverseMercator"): f.write(' ScaleFactor = %6.5f\n' % TMscale) f.write(' TargetName = %s\n' % target) f.write(' EquatorialRadius = %.1f <meters>\n' % semiMajor) f.write(' PolarRadius = %.1f <meters>\n' % semiMinor) if EQUAL(mapProjection, "TransverseMercator"): f.write(' LatitudeType = Planetographic\n') else: f.write(' LatitudeType = Planetocentric\n') f.write(' LongitudeDirection = PositiveEast\n') if (force360 or (lrx > 180)): f.write(' LongitudeDomain = 360\n') else: f.write(' LongitudeDomain = 180\n') f.write(' PixelResolution = %.8f <meters/pixel>\n' % mres) f.write(' Scale = %.4f <pixel/degree>\n' % mapres) if lry < uly: f.write(' MinimumLatitude = %.8f\n' % lry) f.write(' MaximumLatitude = %.8f\n' % uly) else: f.write(' MinimumLatitude = %.8f\n' % uly) f.write(' MaximumLatitude = %.8f\n' % lry) #push into 360 domain (for Astropedia) if (force360): if (ulx < 0): ulx = ulx + 360 if (lrx < 0): lrx = lrx + 360 if lrx < ulx: f.write(' MinimumLongitude = %.8f\n' % lrx) f.write(' MaximumLongitude = %.8f\n' % ulx) else: f.write(' MinimumLongitude = %.8f\n' % ulx) f.write(' MaximumLongitude = %.8f\n' % lrx) f.write(' UpperLeftCornerX = %.6f <meters>\n' % (UpperLeftCornerX)) f.write(' UpperLeftCornerY = %.6f <meters>\n' % (UpperLeftCornerY)) f.write(' End_Group\n') f.write('End_Object\n') f.write('\n') f.write('Object = Label\n') #NOT correct f.write(' Bytes = 256\n') f.write('End_Object\n') f.write('\n') f.write('Object = History\n') f.write(' Name = IsisCube\n') f.write(' StartByte = 1\n') #NOT correct f.write(' Bytes = 0\n') f.write(' ^History = %s\n' % dst_hst) f.write('End_Object\n') f.write('End\n') f.close() #remove history until we fix the size. This is causing issues with cathist #f_hst.write('Object = Astropedia_gdal2isis.py\n') #f_hst.write(' Version = 0.1\n') #f_hst.write(' ProgramVersion = 2013-06-05\n') #f_hst.write(' ExecutionDateTime = %s\n' % str(datetime.datetime.now().isoformat())) #f_hst.write(' Description = \"Convert GDAL supported image to an ISIS detached label and raw image\"\n') #f_hst.write('End_Object\n') f_hst.close() ######################### #Export out raw image ######################### #Setup the output dataset print(' - ISIS3 label created: %s' % dst_lbl) print(' - ISIS3 history created: %s' % dst_hst) if bMakeImage: print('Please wait, writing out raw image: %s' % dst_cub) driver = gdal.GetDriverByName('ENVI') output = driver.CreateCopy(dst_cub, hDataset, 1) if attach: #print 'sleeping 5 seconds' #time.sleep(5) cmd = "/usgs/cdev/contrib/bin/run_cubeatt.sh %s %s" % (dst_lbl, attach_cub) #cmd = "cubeatt from=%s to=%s\n" % (dst_lbl, attach_cub) print cmd #subprocess.call(cmd, shell=True) os.system(cmd) os.remove(dst_cub) os.remove(dst_lbl) os.remove(dst_hst) os.remove(dst_hdr) os.remove(dst_aux) print('Complete') return 0
def _bandReport(hDataset, iBand, verbose, bComputeMinMax, bApproxStats, bStats, bReportStemleaf, bComputeChecksum, bShowMetadata, bShowRAT): hBand = hDataset.GetRasterBand(iBand ) (nBlockXSize, nBlockYSize) = hBand.GetBlockSize() d_type = gdal.GetDataTypeName(hBand.DataType) c_interp = gdal.GetColorInterpretationName(hBand.GetRasterColorInterpretation()) if verbose: print( "Band %d Block=%dx%d Type=%s, ColorInterp=%s" % ( iBand, nBlockXSize, nBlockYSize, d_type, c_interp )) desc = hBand.GetDescription() if desc is not None and len(desc) > 0 and verbose: print( " Description = %s" % desc ) 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 += ("Min=%.3f " % dfMin) if dfMax is not None: line += ("Max=%.3f " % dfMax) if bComputeMinMax: gdal.ErrorReset() adfCMinMax = hBand.ComputeRasterMinMax(False) if gdal.GetLastErrorType() == gdal.CE_None: line += ( " Computed Min/Max=%.3f,%.3f" % ( \ adfCMinMax[0], adfCMinMax[1] )) if verbose: 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 and verbose: print( " Minimum=%.3f, Maximum=%.3f, Mean=%.3f, StdDev=%.3f" % ( \ stats[0], stats[1], stats[2], stats[3] )) if bReportStemleaf: hist = hBand.GetDefaultHistogram(force=True, callback=gdal.TermProgress) if hist is not None and verbose: dfMin = hist[0] dfMax = hist[1] nBucketCount = hist[2] panHistogram = hist[3] _stemleafReport(panHistogram) # print( " %d buckets from %g to %g:" % ( \ # nBucketCount, dfMin, dfMax )) # line = ' ' # for bucket in panHistogram: # line += ("%d " % bucket) # # if verbose: print(line) checksum = hBand.Checksum() if bComputeChecksum and verbose: print( " Checksum=%d" % checksum) dfNoData = hBand.GetNoDataValue() if dfNoData is not None and verbose: 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 += ", " hOverview = hBand.GetOverview( iOverview ); if hOverview is not None: 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 += "*" else: line += "(null)" if verbose: print(line) if bComputeChecksum: line = " Overviews checksum: " for iOverview in range(hBand.GetOverviewCount()): if iOverview != 0: line += ", " hOverview = hBand.GetOverview( iOverview ); if hOverview is not None: line += ( "%d" % hOverview.Checksum()) else: line += "(null)" if verbose: print(line) if hBand.HasArbitraryOverviews() and verbose: 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 += "PER_DATASET " if (nMaskFlags & gdal.GMF_ALPHA) != 0: line += "ALPHA " if (nMaskFlags & gdal.GMF_NODATA) != 0: line += "NODATA " if (nMaskFlags & gdal.GMF_ALL_VALID) != 0: line += "ALL_VALID " if verbose: 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 += ", " hOverview = hMaskBand.GetOverview( iOverview ); if hOverview is not None: line += ( "%d" % hOverview.Checksum()) else: line += "(null)" unitType = hBand.GetUnitType() if len(unitType) > 0 and verbose: print( " Unit Type: %s" % unitType) papszCategories = hBand.GetRasterCategoryNames() if papszCategories is not None and verbose: print( " Categories:" ); i = 0 for category in papszCategories: print( " %3d: %s" % (i, category) ) i += 1 if hBand.GetScale() != 1.0 or hBand.GetOffset() != 0.0 and verbose: 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 and verbose: 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 and verbose: 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 and verbose: 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() return { 'BandNum': iBand, 'BlockSize': (nBlockXSize, nBlockYSize), 'Type': d_type, 'ColorInterp': c_interp, 'Minimum': dfMin, 'Maximum': dfMax, 'Description': desc, 'CheckSum': checksum, 'NoDataValue': dfNoData, 'MaskFlags': nMaskFlags, 'UnitType': unitType, 'Categories:': papszCategories, 'Metadata': hBand.GetMetadata_Dict(), 'ColorTable': hTable, 'RAT': hBand.GetDefaultRAT()}
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 get_info(filename, full_report=True): #, argv=None): bComputeMinMax = False bShowGCPs = True bShowMetadata = True bShowRAT = True bStats = False bApproxStats = True bShowColorTable = True bComputeChecksum = False bReportHistograms = False pszFilename = None papszExtraMDDomains = [] projection = None hTransform = None bShowFileList = True info = {} # 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 = [filename] # # # argv = gdal.GeneralCmdLineProcessor(argv) # # if argv is None: # return 1 # # nArgc = len(argv) # -------------------------------------------------------------------- # Parse arguments. # # -------------------------------------------------------------------- # i = 1 # while i < nArgc: # # if string_equal(argv[i], "--utility_version"): # print("%s is running against GDAL %s" % # (argv[0], gdal.VersionInfo("RELEASE_NAME"))) # return 0 # info["GdalVersionInfo"] # elif string_equal(argv[i], "-mm"): # bComputeMinMax = True # elif string_equal(argv[i], "-hist"): # bReportHistograms = True # elif string_equal(argv[i], "-stats"): # bStats = True # bApproxStats = False # elif string_equal(argv[i], "-approx_stats"): # bStats = True # bApproxStats = True # elif string_equal(argv[i], "-checksum"): # bComputeChecksum = True # elif string_equal(argv[i], "-nogcp"): # bShowGCPs = False # elif string_equal(argv[i], "-nomd"): # bShowMetadata = False # elif string_equal(argv[i], "-norat"): # bShowRAT = False # elif string_equal(argv[i], "-noct"): # bShowColorTable = False # elif string_equal(argv[i], "-mdd") and i < nArgc - 1: # i = i + 1 # papszExtraMDDomains.append(argv[i]) # elif string_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 dataset = gdal.Open(filename, gdal.GA_ReadOnly) if dataset is None: info["Error"] = f"gdalinfo failed - unable to open '{filename}'" return info # general info driver = dataset.GetDriver() info["Driver"] = f"{driver.ShortName} : {driver.LongName}" file_list = dataset.GetFileList() info["Files"] = "none associated" if not file_list else file_list info["Size X"] = dataset.RasterXSize info["Size Y"] = dataset.RasterYSize # projection projection = dataset.GetProjectionRef() if projection is not None: srs = osr.SpatialReference() if srs.ImportFromWkt(projection) == gdal.CE_None: projection = srs.ExportToPrettyWkt(False) projection = projection.strip().strip("\n").strip("\t") else: projection = "Not defined" info["SRS"] = projection # geotransform geo_transform = dataset.GetGeoTransform(can_return_null=True) gt = {} if geo_transform is not None: if geo_transform[2] == 0.0 and geo_transform[4] == 0.0: gt["Origin"] = f"{geo_transform[0]:.15f}, {geo_transform[3]:.15f}" # print("Origin = (%.15f,%.15f)" % ( # geo_transform[0], geo_transform[3])) gt["Pixel Size"] = f"{geo_transform[1]:.15f}, {geo_transform[5]:.15f}" # print("Pixel Size = (%.15f,%.15f)" % ( # geo_transform[1], geo_transform[5])) else: gt["transform"] = f"{geo_transform[0]:.16g}, {geo_transform[1]:.16g}, {geo_transform[2]:.16g}, {geo_transform[3]:.16g}, {geo_transform[4]:.16g}, {geo_transform[5]:.16g}" # print("GeoTransform =\n" # " %.16g, %.16g, %.16g\n" # " %.16g, %.16g, %.16g" % ( # geo_transform[0], # geo_transform[1], # geo_transform[2], # geo_transform[3], # geo_transform[4], # geo_transform[5])) info["geotransform"] = gt # GCPs gcps = {} if bShowGCPs and dataset.GetGCPCount() > 0: projection = dataset.GetGCPProjection() if projection is not None: srs = osr.SpatialReference() if srs.ImportFromWkt(projection) == gdal.CE_None: projection = srs.ExportToPrettyWkt(False) # print("GCP Projection = \n%s" % pretty_wkt) # # else: # print("GCP Projection = %s" % # projection) gcps["projection"] = projection return str(info) # TODO # gcs = dataset.GetGCPs() # i = 0 # for gcp in gcs: # gcs[i] = f"{},{},{},{},{},{},{},{}" # # 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 info["GCPs"] = gcps # -------------------------------------------------------------------- # Report metadata. # -------------------------------------------------------------------- if bShowMetadata: papszMetadata = dataset.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 = dataset.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 = dataset.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 = dataset.GetMetadata_List("SUBDATASETS") if papszMetadata: print("Subdatasets:") for metadata in papszMetadata: print(" %s" % metadata) # -------------------------------------------------------------------- # Report geolocation. # -------------------------------------------------------------------- if bShowMetadata: papszMetadata = dataset.GetMetadata_List("GEOLOCATION") else: papszMetadata = None if bShowMetadata and papszMetadata: print("Geolocation:") for metadata in papszMetadata: print(" %s" % metadata) # -------------------------------------------------------------------- # Report RPCs # -------------------------------------------------------------------- if bShowMetadata: papszMetadata = dataset.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 projection: hProj = osr.SpatialReference(projection) 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(dataset, hTransform, "Upper Left", 0.0, 0.0) GDALInfoReportCorner(dataset, hTransform, "Lower Left", 0.0, dataset.RasterYSize) GDALInfoReportCorner(dataset, hTransform, "Upper Right", dataset.RasterXSize, 0.0) GDALInfoReportCorner(dataset, hTransform, "Lower Right", dataset.RasterXSize, dataset.RasterYSize) GDALInfoReportCorner(dataset, hTransform, "Center", dataset.RasterXSize / 2.0, dataset.RasterYSize / 2.0) # ==================================================================== # Loop over bands. # ==================================================================== for iBand in range(dataset.RasterCount): hBand = dataset.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 string_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(argv=None): bComputeMinMax = False bSample = False bShowGCPs = True bShowMetadata = True bShowRAT = False debug = False bStats = False bApproxStats = True bShowColorTable = True bComputeChecksum = False bReportHistograms = False pszFilename = None papszExtraMDDomains = [] pszProjection = None hTransform = None bShowFileList = True dst_xml = None template_xml = None bands = 1 iOverview = 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], "-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 template_xml is None: template_xml = argv[i] elif dst_xml is None: dst_xml = argv[i] else: return Usage(argv[0]) i = i + 1 if pszFilename is None: return Usage(argv[0]) if template_xml is None: return Usage(argv[0]) if dst_xml is None: return Usage(argv[0]) #/* -------------------------------------------------------------------- */ #/* Open GDAL dataset. */ #/* -------------------------------------------------------------------- */ hDataset = gdal.Open(pszFilename, gdal.GA_ReadOnly) if hDataset is None: print("gdalinfo failed - unable to open '%s'." % pszFilename) sys.exit(1) #/* -------------------------------------------------------------------- */ #/* load XML template file (generally fgdc-template.xml) */ #/* -------------------------------------------------------------------- */ parser = etree.XMLParser(remove_blank_text=True) tree = etree.parse(template_xml, parser) for lworkcit in tree.getiterator('lworkcit'): for citeinfo in lworkcit.getiterator('citeinfo'): title = citeinfo.find('title') if title is None: title = etree.SubElement(citeinfo, 'title') title.text = pszFilename #/* -------------------------------------------------------------------- */ #/* 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) mapProjection = "None" #Extract projection information target = hSRS.GetAttrValue("DATUM", 0).replace("D_", "").replace("_2000", "") semiMajor = hSRS.GetSemiMajor() #/ 1000.0 semiMinor = hSRS.GetSemiMinor() #/ 1000.0 invFlat = hSRS.GetInvFlattening() if (pszProjection[0:6] == "GEOGCS"): mapProjection = "SIMPLE_CYLINDRICAL" centLat = 0 centLon = 0 if (pszProjection[0:6] == "PROJCS"): mapProjection = hSRS.GetAttrValue("PROJECTION", 0) for horizsys in tree.getiterator('horizsys'): horizsys.clear() planar = etree.SubElement(horizsys, 'planar') mapproj = etree.SubElement(planar, 'mapproj') mapprojn = etree.SubElement(mapproj, 'mapprojn') if EQUAL(mapProjection, "Equirectangular"): #for mapprojn in tree.getiterator('mapprojn'): mapprojn.text = "Equirectangular" centLat = None centLat = hSRS.GetProjParm('standard_parallel_1') if centLat == None: centLat = hSRS.GetProjParm('latitude_of_origin') centLon = hSRS.GetProjParm('central_meridian') equirect = etree.SubElement(mapproj, 'equirect') #for equirect in tree.getiterator('equirect'): stdparll = etree.SubElement(equirect, 'stdparll') #for stdparll in equirect.getiterator('stdparll'): stdparll.text = str(centLat) #for longcm in equirect.getiterator('longcm'): longcm = etree.SubElement(equirect, 'longcm') longcm.text = str(centLon) #for feast in equirect.getiterator('feast'): feast = etree.SubElement(equirect, 'feast') feast.text = str(hSRS.GetProjParm('false_easting')) #for fnorth in equirect.getiterator('fnorth'): fnorth = etree.SubElement(equirect, 'fnorth') fnorth.text = str(hSRS.GetProjParm('false_northing')) # Change to building projection XML section instead of replace # Change to merc instead of transmer if EQUAL(mapProjection, "Mercator"): for mapprojn in tree.getiterator('mapprojn'): mapprojn.text = "Mercator" centLat = None centLat = hSRS.GetProjParm('latitude_of_origin') if centLat == None: centLat = hSRS.GetProjParm('standard_parallel_1') centLon = hSRS.GetProjParm('central_meridian') scale = hSRS.GetProjParm('scale_factor') for merc in tree.getiterator('transmer'): for stdparll in merc.getiterator('stdparll'): stdparll.text = str(centLat) for longcm in merc.getiterator('longcm'): longcm.text = str(centLon) for sfequat in merc.getiterator('sfequat'): sfequat.text = str(scale) for feast in merc.getiterator('feast'): feast.text = str(hSRS.GetProjParm('false_easting')) for fnorth in merc.getiterator('fnorth'): fnorth.text = str( hSRS.GetProjParm('false_northing')) # Change to building projection XML section instead of replace if EQUAL(mapProjection, "Orthographic "): for mapprojn in tree.getiterator('mapprojn'): mapprojn.text = "Orthographic" centLat = hSRS.GetProjParm('latitude_of_origin ') centLon = hSRS.GetProjParm('central_meridian') for orthogr in tree.getiterator('orthogr'): for stdparll in orthogr.getiterator('stdparll'): stdparll.text = str(centLat) for longcm in orthogr.getiterator('longcm'): longcm.text = str(centLon) for feast in orthogr.getiterator('feast'): feast.text = str(hSRS.GetProjParm('false_easting')) for fnorth in orthogr.getiterator('fnorth'): fnorth.text = str( hSRS.GetProjParm('false_northing')) # Change to building projection XML section instead of replace if EQUAL(mapProjection, "Stereographic"): for mapprojn in tree.getiterator('mapprojn'): mapprojn.text = "Stereographic" centLat = hSRS.GetProjParm('latitude_of_origin') centLon = hSRS.GetProjParm('central_meridian') for stereo in tree.getiterator('stereo'): for latprjc in stereo.getiterator('latprjc'): latprjc.text = str(centLat) for longpc in stereo.getiterator('longpc'): longpc.text = str(centLon) for feast in stereo.getiterator('feast'): feast.text = str(hSRS.GetProjParm('false_easting')) for fnorth in stereo.getiterator('fnorth'): fnorth.text = str( hSRS.GetProjParm('false_northing')) # Change to building projection XML section instead of replace if EQUAL(mapProjection, "Sinusoidal"): for mapprojn in tree.getiterator('mapprojn'): mapprojn.text = "Sinusoidal" centLon = None centLon = hSRS.GetProjParm('longitude_of_center') if centLon == None: centLon = hSRS.GetProjParm('central_meridian') for sinusoid in tree.getiterator('sinusoid'): for longcm in sinusoid.getiterator('longcm'): longcm.text = str(centLon) for feast in sinusoid.getiterator('feast'): feast.text = str(hSRS.GetProjParm('false_easting')) for fnorth in sinusoid.getiterator('fnorth'): fnorth.text = str( hSRS.GetProjParm('false_northing')) # Change to building projection XML section instead of replace if EQUAL(mapProjection, "Robinson"): for mapprojn in tree.getiterator('mapprojn'): mapprojn.text = "Robinson" centLon = None centLon = hSRS.GetProjParm('longitude_of_center') if centLon == None: centLon = hSRS.GetProjParm('central_meridian') for robinson in tree.getiterator('robinson'): for longpc in robinson.getiterator('longpc'): longpc.text = str(centLon) for feast in robinson.getiterator('feast'): feast.text = str(hSRS.GetProjParm('false_easting')) for fnorth in robinson.getiterator('fnorth'): fnorth.text = str( hSRS.GetProjParm('false_northing')) # Change to building projection XML section instead of replace if (EQUAL(mapProjection, "Polar_Stereographic") or EQUAL(mapProjection, "Stereographic_North_Pole") or EQUAL(mapProjection, "Stereographic_South_Pole")): for mapprojn in tree.getiterator('mapprojn'): mapprojn.text = "Polar Stereographic" centLat = hSRS.GetProjParm('latitude_of_origin') centLon = hSRS.GetProjParm('central_meridian') scale = hSRS.GetProjParm('scale_factor') for polarst in tree.getiterator('polarst'): for stdparll in polarst.getiterator('stdparll'): stdparll.text = str(centLat) for svlong in polarst.getiterator('svlong'): svlong.text = str(centLon) for sfprjorg in polarst.getiterator('sfprjorg'): sfprjorg.text = str(scale) for feast in polarst.getiterator('feast'): feast.text = str(hSRS.GetProjParm('false_easting')) for fnorth in polarst.getiterator('fnorth'): fnorth.text = str( hSRS.GetProjParm('false_northing')) # Change to building projection XML section instead of replace if EQUAL(mapProjection, "Transverse_Mercator"): for mapprojn in tree.getiterator('mapprojn'): mapprojn.text = "Transverse Mercator" centLat = hSRS.GetProjParm('latitude_of_origin') centLon = hSRS.GetProjParm('central_meridian') scale = hSRS.GetProjParm('scale_factor') for transmer in tree.getiterator('transmer'): for latprjo in transmer.getiterator('latprjo'): latprjo.text = str(centLat) for longcm in transmer.getiterator('longcm'): longcm.text = str(centLon) for sfctrmer in transmer.getiterator('sfctrmer'): sfctrmer.text = str(scale) for feast in transmer.getiterator('feast'): feast.text = str(hSRS.GetProjParm('false_easting')) for fnorth in transmer.getiterator('fnorth'): fnorth.text = str( hSRS.GetProjParm('false_northing')) #Create cellsize block for all projections planci = etree.SubElement(planar, 'planci') plance = etree.SubElement(planci, 'plance') plance.text = 'row and column' coordrep = etree.SubElement(planci, 'coordrep') absres = etree.SubElement(coordrep, 'absres') ordres = etree.SubElement(coordrep, 'ordres') plandu = etree.SubElement(planci, 'plandu') 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] lonres = adfGeoTransform[1] latres = adfGeoTransform[5] kmres = adfGeoTransform[1] * (semiMajor * math.pi / 180.0) / 1000.0 else: #convert m/pixel to pixel/degree mapres = 1 / (adfGeoTransform[1] / (semiMajor * math.pi / 180.0)) lonres = adfGeoTransform[1] / (semiMajor * math.pi / 180.0) latres = adfGeoTransform[5] / (semiMajor * math.pi / 180.0) xres = adfGeoTransform[1] yres = adfGeoTransform[5] 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) (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 ); if iOverview is not None: 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 ); #/************************************************************************/ #/* WriteXML bits to FGDC template */ #/************************************************************************/ for rasttype in tree.getiterator('rasttype'): rasttype.text = "Pixel" hBand = hDataset.GetRasterBand(1) for ellips in tree.getiterator('ellips'): ellips.text = target for semiaxis in tree.getiterator('semiaxis'): semiaxis.text = str(semiMajor) for denflat in tree.getiterator('denflat'): denflat.text = str(invFlat) if (pszProjection[0:6] == "GEOGCS"): for latSize in tree.getiterator('latres'): latSize.text = str(latres) if debug: print 'Lat resolution: %s' % (latSize.text) for lonSize in tree.getiterator('lonres'): lonSize.text = str(lonres) for geogunit in tree.getiterator('geogunit'): geogunit.text = "Decimal degrees" else: for absres in tree.getiterator('absres'): # in meters absres.text = str(xres) if debug: print 'X resolution: %s' % (absres.text) for ordres in tree.getiterator('ordres'): ordres.text = str(abs(yres)) for plandu in tree.getiterator('plandu'): plandu.text = "meters" for southbc in tree.getiterator('southbc'): southbc.text = str(lry) for northbc in tree.getiterator('northbc'): northbc.text = str(uly) for westbc in tree.getiterator('westbc'): westbc.text = str(ulx) for eastbc in tree.getiterator('eastbc'): eastbc.text = str(lrx) for rowcount in tree.getiterator('rowcount'): rowcount.text = str(hDataset.RasterYSize) for colcount in tree.getiterator('colcount'): colcount.text = str(hDataset.RasterYSize) for vrtcount in tree.getiterator('vrtcount'): vrtcount.text = str(hDataset.RasterCount) for metstdn in tree.getiterator('metstdn'): metstdn.text = "FGDC Content Standards for Digital Geospatial Metadata" for metstdv in tree.getiterator('metstdv'): metstdv.text = "FGDC-STD-001-1998" #/* ==================================================================== */ #/* writeout sparse XML for merging */ #/* ==================================================================== */ try: #tree.write(dst_xml, pretty_print=True, xml_declaration=True) #mp doesn't like declaration tree.write(dst_xml, pretty_print=True) except ImportError: print("Failed to write out XML document") return 0
def main(rfile): graster = gdal.Open(rfile) band = graster.GetRasterBand(1) stats = band.GetStatistics(True, True) def EQUAL(a, b): return a.lower() == b.lower() 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 ######################################################## ######################################################## #bReportHistograms = True #-hist bStats = True #-stats bApproxStats = True #-stats hDataset = gdal.Open(rfile, 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 len(papszFileList) == 0: 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 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. # -------------------------------------------------------------------- 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) (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: pass #hRAT = hBand.GetDefaultRAT() #GDALRATDumpReadable( hRAT, None ); return 0