Example #1
0
def compare_band(golden_band, new_band, ident, options=None):
    found_diff = 0

    options = [] if options is None else options

    if golden_band.DataType != new_band.DataType:
        print('Band %s pixel types differ.' % ident)
        print('  Golden: ' + gdal.GetDataTypeName(golden_band.DataType))
        print('  New:    ' + gdal.GetDataTypeName(new_band.DataType))
        found_diff += 1

    if golden_band.GetNoDataValue() != new_band.GetNoDataValue():
        print('Band %s nodata values differ.' % ident)
        print('  Golden: ' + str(golden_band.GetNoDataValue()))
        print('  New:    ' + str(new_band.GetNoDataValue()))
        found_diff += 1

    if golden_band.GetColorInterpretation() != new_band.GetColorInterpretation(
    ):
        print('Band %s color interpretation values differ.' % ident)
        print('  Golden: ' + gdal.GetColorInterpretationName(
            golden_band.GetColorInterpretation()))
        print(
            '  New:    ' +
            gdal.GetColorInterpretationName(new_band.GetColorInterpretation()))
        found_diff += 1

    if golden_band.Checksum() != new_band.Checksum():
        print('Band %s checksum difference:' % ident)
        print('  Golden: ' + str(golden_band.Checksum()))
        print('  New:    ' + str(new_band.Checksum()))
        found_diff += 1
        compare_image_pixels(golden_band, new_band, ident, options)

    # Check overviews
    if golden_band.GetOverviewCount() != new_band.GetOverviewCount():
        print('Band %s overview count difference:' % ident)
        print('  Golden: ' + str(golden_band.GetOverviewCount()))
        print('  New:    ' + str(new_band.GetOverviewCount()))
        found_diff += 1
    else:
        for i in range(golden_band.GetOverviewCount()):
            found_diff += compare_band(golden_band.GetOverview(i),
                                       new_band.GetOverview(i),
                                       ident + ' overview ' + str(i), options)

    # Metadata
    if 'SKIP_METADATA' not in options:
        found_diff += compare_metadata(golden_band.GetMetadata(),
                                       new_band.GetMetadata(), 'Band ' + ident,
                                       options)

    # TODO: Color Table, gain/bias, units, blocksize, mask, min/max

    return found_diff
Example #2
0
def compare_band(golden_band, new_band, id):
  found_diff = 0

  if golden_band.DataType != new_band.DataType:
    print 'Band %s pixel types differ.'
    print '  Golden:', gdal.GetDataTypeName(golden_band.DataType)
    print '  New:   ', gdal.GetDataTypeName(new_band.DataType)
    found_diff += 1

  if golden_band.GetNoDataValue() != new_band.GetNoDataValue():
    print 'Band %s nodata values differ.'
    print '  Golden:', golden_band.GetNoDataValue()
    print '  New:   ', new_band.GetNoDataValue()
    found_diff += 1

  if golden_band.GetColorInterpretation() != new_band.GetColorInterpretation():
    print 'Band %s color interpretation values differ.'
    print '  Golden:', gdal.GetColorInterpretationName(golden_band.GetColorInterpretation())
    print '  New:   ', gdal.GetColorInterpretationName(new_band.GetColorInterpretation())
    found_diff += 1

  if golden_band.Checksum() != new_band.Checksum():
    print 'Band %s checksum difference:' % id
    print '  Golden:', golden_band.Checksum()
    print '  New:   ', new_band.Checksum()
    found_diff += 1
    compare_image_pixels(golden_band,new_band, id)

  # Check overviews
  if golden_band.GetOverviewCount() != new_band.GetOverviewCount():
    print 'Band %s overview count difference:' % id
    print '  Golden:', golden_band.GetOverviewCount()
    print '  New:   ', new_band.GetOverviewCount()
    found_diff += 1
  else:
    for i in range(golden_band.GetOverviewCount()):
      compare_band(golden_band.GetOverview(i),
                   new_band.GetOverview(i),
                   id + ' overview ' + str(i))

  # Metadata
  found_diff += compare_metadata(golden_band.GetMetadata(),
                                 new_band.GetMetadata(),
                                 'Band ' + id)

  # TODO: Color Table, gain/bias, units, blocksize, mask, min/max

  return found_diff
Example #3
0
    def get_fields_range_type(self):
        """
        Returns the range type fields from a dataset
        :rtype: list[GDALField]
        """
        import osgeo.gdal as gdal

        fields = []

        number_of_bands = self.gdal_dataset.RasterCount

        for i in range(1, number_of_bands + 1):
            band = self.gdal_dataset.GetRasterBand(i)

            # Get the field name
            if band.GetColorInterpretation():
                field_name = gdal.GetColorInterpretationName(band.GetColorInterpretation())
            else:
                field_name = ConfigManager.default_field_name_prefix + repr(i)

            if len(ConfigManager.default_null_values) > 0:
                nil_values = ConfigManager.default_null_values
            else:
                # If not, then detects it from file's bands
                nil_value = repr(band.GetNoDataValue()) if band.GetNoDataValue() is not None else ""
                nil_values = [nil_value]

            # Get the unit of measure
            uom = band.GetUnitType() if band.GetUnitType() else ConfigManager.default_unit_of_measure

            # Add it to the list of fields
            fields.append(GDALField(field_name, uom, nil_values))

        return fields
Example #4
0
def get_color_interpretations(filepath):
    dataset = open_raster_file(filepath)
    result = []
    for band_id in range(1, dataset.RasterCount + 1):
        band = dataset.GetRasterBand(band_id)
        color_interpretation = gdal.GetColorInterpretationName(
            band.GetColorInterpretation())
        result.append(color_interpretation)
    return result
Example #5
0
    def getBandInterpretation(self, ds):
        """Get image mode and band interpretation.

        Arguments:
            ds (osgeo.gdal.Dataset): Raster dataset.

        Raises:
            NotImplementedError: When image mode is not supported.
        Returns:
            (tuple):
                - (str): image mode; one of 'grayscale', 'RGB', 'RGBA', 'Palette'.
                - (dict): Band interpretation; dictionary with key the color name and value the band number.
        """
        count = ds.RasterCount
        bandInterp = {}
        for i in range(count):
            i += 1
            band = ds.GetRasterBand(i)
            if band is None:
                continue
            color = gdal.GetColorInterpretationName(band.GetColorInterpretation())
            if color in ['Red', 'Green', 'Blue', 'Gray', 'Alpha', 'Palette']:
                bandInterp[color] = i
        colors = list(bandInterp.keys())
        if 'Gray' in colors:
            mode = 'grayscale'
        elif 'Red' in colors and 'Green' in colors and 'Blue' in colors and len(colors) == 3:
            mode = 'RGB'
            if count == 4 and 4 not in list(bandInterp.values()):
                band = ds.GetRasterBand(4)
                color = gdal.GetColorInterpretationName(band.GetColorInterpretation())
                max_value = band.GetStatistics(False, True)[1]
                if color == 'Undefined' and max_value < 256:
                    mode = 'RGBA'
                    bandInterp['Alpha'] = 4
        elif 'Red' in colors and 'Green' in colors and 'Blue' in colors and 'Alpha' in colors and len(colors) == 4:
            mode = 'RGBA'
        elif 'Palette' in colors:
            mode = 'Palette'
        else:
            raise NotImplementedError('Only Grayscale, RGB(A), and color-mapped rasters are supported.')
        return (mode, bandInterp)
Example #6
0
def map_gci_list_to_names(gci_list):
    """
    Translate a sequence of GDAL GCI values into a list of their string names.

    Pre-condition: Integers provided are valid color interpretation constants.

    :param collections.Iterable[int] gci_list:
        Integer GDAL color interpretation integer constants sequence.
    :return: List of o the string names for each color interpretation constant
        provided
    :rtype: list[str]
    """
    return [gdal.GetColorInterpretationName(gci_int) for gci_int in gci_list]
Example #7
0
    def detect_message(self, file):
        """Detect the invisible message embedded to the file.

        Arguments:
            file (str): Path of the image file.

        Returns:
            (str): The embedded message.
        """
        wm = Watermark(file)
        bitmap = None

        bands = wm._get_color_bands_no()
        for band_no in bands:
            band_wm = wm.raster.GetRasterBand(band_no)
            color = gdal.GetColorInterpretationName(band_wm.GetColorInterpretation())
            try:
                band = self.raster.GetRasterBand(self.band_interpretation[color])
            except KeyError:
                continue
            LL3, (LH3, HL3, HH3), C2, C1 = pywt.wavedec2(band.ReadAsArray(), 'haar', level=3)
            LL3w, (LH3w, HL3w, HH3w), C2, C1 = pywt.wavedec2(band_wm.ReadAsArray(), 'haar', level=3)
            dim = min(np.shape(HH3))
            if bitmap is None:
                bitmap = np.array([np.array([0.]*dim)]*dim)

            alpha = np.mean(np.abs(HH3))
            for x in np.arange(0, dim):
                for y in np.arange(0, dim):
                    try:
                        bitmap[x][y] += (HH3w[x][y] - HH3[x][y])/alpha
                    except IndexError:
                        pass

        if bitmap is None:
            return None
        def arrayToBool(elem):
            return True if elem >= 0 else False
        arrayToBoolVec = np.vectorize(arrayToBool)

        bitmap = unscramble(arrayToBoolVec(bitmap), iterations=20)
        img = Image.fromarray(bitmap)
        try:
            message = decode(img)[0].data.decode()
        except IndexError:
            message = None

        return message
def get_band_info(dataset):
    bands = []
    for i in range(dataset.RasterCount):
        band_info = {}
        band = dataset.GetRasterBand(i + 1)
        color = band.GetColorInterpretation()
        colorInterp = gdal.GetColorInterpretationName(color)
        band_info['dataType'] = gdal.GetDataTypeName(band.DataType)
        band_info['colorInterpretation'] = colorInterp
        band_info['scale'] = band.GetScale()
        band_info['offset'] = band.GetOffset()
        band_info['noData'] = band.GetNoDataValue()
        band_info['units'] = band.GetUnitType()
        bands.append(band_info)

    return bands
Example #9
0
def transparent_image(color_relief_name,
                      hillshade_name,
                      outfile_name,
                      verbose=False):
    v = verbose
    hillshade = osgeo.gdal.Open(hillshade_name, osgeo.gdal.GA_ReadOnly)
    color = osgeo.gdal.Open(color_relief_name, osgeo.gdal.GA_ReadOnly)

    w1, h1 = color.RasterXSize, color.RasterYSize
    w2, h2 = hillshade.RasterXSize, hillshade.RasterYSize
    if v: print('dim: color:', w1, h1, '\t\thillshade:', w2, h2)
    if w1 != w2 or h1 != h2:
        print('ERROR: width and height must be the same.  Found (', w1, h1,
              ') and (', w2, h2, ')')
        return False

    driver = gdal.GetDriverByName('GTiff')
    if driver is None:
        print('ERROR: Format driver %s not found, pick a supported driver.' %
              format)
        return False

    dst = driver.CreateCopy(outfile_name, color)  #, 0) # 0 For GeoTiff

    if v:
        print('gdal.GCI_AlphaBand:', gdal.GCI_AlphaBand)
        for band_num in range(1, color.RasterCount + 1):
            band = color.GetRasterBand(band_num)
            if band is None:
                print('band is None')
                continue
            bandmin, bandmax = band.ComputeRasterMinMax()
            clr_interp = band.GetColorInterpretation()
            print('color_band_info:', band_num, bandmin, bandmax, clr_interp,
                  gdal.GetColorInterpretationName(clr_interp))

    alpha = color.GetRasterBand(4)
    gray_band = hillshade.GetRasterBand(1)

    # Shove all the same gray values into all the color channels
    for band_num in range(1, 4):
        dst.GetRasterBand(band_num).WriteArray(gray_band.ReadAsArray())

    # Set the alpha
    dst.GetRasterBand(4).WriteArray(alpha.ReadAsArray())

    return True
    def get_fields(self):
        """
        Returns the range type fields from a gdal dataset

        :return: a list of range type fields in gml format
        """
        import osgeo.gdal as gdal
        fields = []
        for i in range(1, self.gdal_dataset.RasterCount + 1):
            template = self.range_type_template
            band = self.gdal_dataset.GetRasterBand(i)

            # Add the null values to the template
            if band.GetNoDataValue() is not None:
                template = template.replace("$VarNillReason", "None")
                template = template.replace("$VarNillValues", """<swe:nilValues>
                        <swe:NilValues>
                            <swe:nilValue reason="">""" + str(band.GetNoDataValue()) + """</swe:nilValue>
                        </swe:NilValues>
                    </swe:nilValues>""")
            else:
                template = template.replace("$VarNillValues", "")

            # Add the color interpretation to the template
            if band.GetColorInterpretation() is not None:
            	bandName = gdal.GetColorInterpretationName(band.GetColorInterpretation())
            	if bandName.lower() == "undefined":
            		bandName = "field_" + str(i)
                template = template.replace("$VarFieldName", bandName)
            else:
                template = template.replace("$VarFieldName", "")

            # We cannot extract this information yet and is not mandatory in GML so ommit it for the moment
            template = template.replace("$VarFieldDefinition", "")
            template = template.replace("$VarFieldDescription", "")

            # Add the units of measure to template
            if band.GetUnitType() is not None:
                template = template.replace("$VarUomCode", band.GetUnitType())
            else:
                template = template.replace("$VarUomCode", "")

            fields.append(template)

        return fields
Example #11
0
 def _apply(band, scope, **kwargs):
     if scope == 'statistics':
         bApproxOK = kwargs.pop('bApproxOK', False)
         bForce = kwargs.pop('bForce', True)
         return dict(zip(['min', 'max', 'mean', 'std'], band.GetStatistics(bApproxOK, bForce, **kwargs)))
     elif scope == 'defaultHistogram':
         return band.GetDefaultHistogram(**kwargs)
     elif scope == 'histogram':
         return band.GetHistogram(**kwargs)
     elif scope == 'datatypes':
         datatype = band.DataType
         return gdal.GetDataTypeName(datatype)
     elif scope == 'noDataValue':
         return band.GetNoDataValue(**kwargs)
     elif scope == 'colorInterpretation':
         color = band.GetColorInterpretation()
         return gdal.GetColorInterpretationName(color)
     else:
         raise Exception('ERROR: Method %s not supported' % (scope))
Example #12
0
def _make_band(root, source_band, vrt_bidx, description=None, vrt_ndv=None):
    # Create <VRTRasterBand>
    band = ET.SubElement(root, 'VRTRasterBand')
    band.set('dataType', _gdal_typename(source_band.dtype))
    band.set('band', str(vrt_bidx))

    # Optional subelements
    # TODO: ColorTable, GDALRasterAttributeTable, UnitType,
    #       Offset, Scale, CategoryNames
    colorinterp = gdal.GetColorInterpretationName(
        source_band.colorinterp.value)
    _make_subelement(band, 'ColorInterp', colorinterp)

    # Output band NDV defaults to source NDV
    vrt_ndv = vrt_ndv if vrt_ndv is not None else source_band.nodata
    if vrt_ndv is not None:
        _make_subelement(band, 'NoDataValue', str(vrt_ndv))

    description = description or source_band.description
    if description:
        band.set('Description', description)

    return band
Example #13
0
def main(argv=None):

    bComputeMinMax = False
    bShowGCPs = True
    bShowMetadata = True
    bShowRAT = True
    bStats = False
    bApproxStats = True
    bShowColorTable = True
    bComputeChecksum = False
    bReportHistograms = False
    pszFilename = None
    papszExtraMDDomains = []
    pszProjection = None
    hTransform = None
    bShowFileList = True

    #/* Must process GDAL_SKIP before GDALAllRegister(), but we can't call */
    #/* GDALGeneralCmdLineProcessor before it needs the drivers to be registered */
    #/* for the --format or --formats options */
    #for( i = 1; i < argc; i++ )
    #{
    #    if EQUAL(argv[i],"--config") and i + 2 < argc and EQUAL(argv[i + 1], "GDAL_SKIP"):
    #    {
    #        CPLSetConfigOption( argv[i+1], argv[i+2] );
    #
    #        i += 2;
    #    }
    #}
    #
    #GDALAllRegister();

    if argv is None:
        argv = sys.argv

    argv = gdal.GeneralCmdLineProcessor(argv)

    if argv is None:
        return 1

    nArgc = len(argv)
    #/* -------------------------------------------------------------------- */
    #/*      Parse arguments.                                                */
    #/* -------------------------------------------------------------------- */
    i = 1
    while i < nArgc:

        if EQUAL(argv[i], "--utility_version"):
            print("%s is running against GDAL %s" %
                  (argv[0], gdal.VersionInfo("RELEASE_NAME")))
            return 0
        elif EQUAL(argv[i], "-mm"):
            bComputeMinMax = True
        elif EQUAL(argv[i], "-hist"):
            bReportHistograms = True
        elif EQUAL(argv[i], "-stats"):
            bStats = True
            bApproxStats = False
        elif EQUAL(argv[i], "-approx_stats"):
            bStats = True
            bApproxStats = True
        elif EQUAL(argv[i], "-checksum"):
            bComputeChecksum = True
        elif EQUAL(argv[i], "-nogcp"):
            bShowGCPs = False
        elif EQUAL(argv[i], "-nomd"):
            bShowMetadata = False
        elif EQUAL(argv[i], "-norat"):
            bShowRAT = False
        elif EQUAL(argv[i], "-noct"):
            bShowColorTable = False
        elif EQUAL(argv[i], "-mdd") and i < nArgc - 1:
            i = i + 1
            papszExtraMDDomains.append(argv[i])
        elif EQUAL(argv[i], "-nofl"):
            bShowFileList = False
        elif argv[i][0] == '-':
            return Usage()
        elif pszFilename is None:
            pszFilename = argv[i]
        else:
            return Usage()

        i = i + 1

    if pszFilename is None:
        return Usage()

#/* -------------------------------------------------------------------- */
#/*      Open dataset.                                                   */
#/* -------------------------------------------------------------------- */
    hDataset = gdal.Open(pszFilename, gdal.GA_ReadOnly)

    if hDataset is None:

        print("gdalinfo failed - unable to open '%s'." % pszFilename)

        return 1

#/* -------------------------------------------------------------------- */
#/*      Report general info.                                            */
#/* -------------------------------------------------------------------- */
    hDriver = hDataset.GetDriver()
    print( "Driver: %s/%s" % ( \
            hDriver.ShortName, \
            hDriver.LongName ))

    papszFileList = hDataset.GetFileList()
    if papszFileList is None or 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
Example #14
0
def gdal_pansharpen(argv):

    argv = gdal.GeneralCmdLineProcessor(argv)
    if argv is None:
        return -1

    pan_name = None
    last_name = None
    spectral_ds = []
    spectral_bands = []
    out_name = None
    bands = []
    weights = []
    frmt = None
    creation_options = []
    callback = gdal.TermProgress_nocb
    resampling = None
    spat_adjust = None
    verbose_vrt = False
    num_threads = None
    bitdepth = None
    nodata = None

    i = 1
    argc = len(argv)
    while i < argc:
        if (argv[i] == '-of' or argv[i] == '-f') and i < len(argv) - 1:
            frmt = argv[i + 1]
            i = i + 1
        elif argv[i] == '-r' and i < len(argv) - 1:
            resampling = argv[i + 1]
            i = i + 1
        elif argv[i] == '-spat_adjust' and i < len(argv) - 1:
            spat_adjust = argv[i + 1]
            i = i + 1
        elif argv[i] == '-b' and i < len(argv) - 1:
            bands.append(int(argv[i + 1]))
            i = i + 1
        elif argv[i] == '-w' and i < len(argv) - 1:
            weights.append(float(argv[i + 1]))
            i = i + 1
        elif argv[i] == '-co' and i < len(argv) - 1:
            creation_options.append(argv[i + 1])
            i = i + 1
        elif argv[i] == '-threads' and i < len(argv) - 1:
            num_threads = argv[i + 1]
            i = i + 1
        elif argv[i] == '-bitdepth' and i < len(argv) - 1:
            bitdepth = argv[i + 1]
            i = i + 1
        elif argv[i] == '-nodata' and i < len(argv) - 1:
            nodata = argv[i + 1]
            i = i + 1
        elif argv[i] == '-q':
            callback = None
        elif argv[i] == '-verbose_vrt':
            verbose_vrt = True
        elif argv[i][0] == '-':
            sys.stderr.write('Unrecognized option : %s\n' % argv[i])
            return Usage()
        elif pan_name is None:
            pan_name = argv[i]
            pan_ds = gdal.Open(pan_name)
            if pan_ds is None:
                return 1
        else:
            if last_name is not None:
                pos = last_name.find(',band=')
                if pos > 0:
                    spectral_name = last_name[0:pos]
                    ds = gdal.Open(spectral_name)
                    if ds is None:
                        return 1
                    band_num = int(last_name[pos + len(',band='):])
                    band = ds.GetRasterBand(band_num)
                    spectral_ds.append(ds)
                    spectral_bands.append(band)
                else:
                    spectral_name = last_name
                    ds = gdal.Open(spectral_name)
                    if ds is None:
                        return 1
                    for j in range(ds.RasterCount):
                        spectral_ds.append(ds)
                        spectral_bands.append(ds.GetRasterBand(j + 1))

            last_name = argv[i]

        i = i + 1

    if pan_name is None or not spectral_bands:
        return Usage()
    out_name = last_name

    if frmt is None:
        frmt = GetOutputDriverFor(out_name)

    if not bands:
        bands = [j + 1 for j in range(len(spectral_bands))]
    else:
        for band in bands:
            if band < 0 or band > len(spectral_bands):
                print('Invalid band number in -b: %d' % band)
                return 1

    if weights and len(weights) != len(spectral_bands):
        print(
            'There must be as many -w values specified as input spectral bands'
        )
        return 1

    vrt_xml = """<VRTDataset subClass="VRTPansharpenedDataset">\n"""
    if bands != [j + 1 for j in range(len(spectral_bands))]:
        for i, band in enumerate(bands):
            sband = spectral_bands[band - 1]
            datatype = gdal.GetDataTypeName(sband.DataType)
            colorname = gdal.GetColorInterpretationName(
                sband.GetColorInterpretation())
            vrt_xml += """  <VRTRasterBand dataType="%s" band="%d" subClass="VRTPansharpenedRasterBand">
      <ColorInterp>%s</ColorInterp>
  </VRTRasterBand>\n""" % (datatype, i + 1, colorname)

    vrt_xml += """  <PansharpeningOptions>\n"""

    if weights:
        vrt_xml += """      <AlgorithmOptions>\n"""
        vrt_xml += """        <Weights>"""
        for i, weight in enumerate(weights):
            if i > 0:
                vrt_xml += ","
            vrt_xml += "%.16g" % weight
        vrt_xml += "</Weights>\n"
        vrt_xml += """      </AlgorithmOptions>\n"""

    if resampling is not None:
        vrt_xml += '      <Resampling>%s</Resampling>\n' % resampling

    if num_threads is not None:
        vrt_xml += '      <NumThreads>%s</NumThreads>\n' % num_threads

    if bitdepth is not None:
        vrt_xml += '      <BitDepth>%s</BitDepth>\n' % bitdepth

    if nodata is not None:
        vrt_xml += '      <NoData>%s</NoData>\n' % nodata

    if spat_adjust is not None:
        vrt_xml += '      <SpatialExtentAdjustment>%s</SpatialExtentAdjustment>\n' % spat_adjust

    pan_relative = '0'
    if frmt.upper() == 'VRT':
        if not os.path.isabs(pan_name):
            pan_relative = '1'
            pan_name = os.path.relpath(pan_name, os.path.dirname(out_name))

    vrt_xml += """    <PanchroBand>
      <SourceFilename relativeToVRT="%s">%s</SourceFilename>
      <SourceBand>1</SourceBand>
    </PanchroBand>\n""" % (pan_relative, pan_name)

    for i, sband in enumerate(spectral_bands):
        dstband = ''
        for j, band in enumerate(bands):
            if i + 1 == band:
                dstband = ' dstBand="%d"' % (j + 1)
                break

        ms_relative = '0'
        ms_name = spectral_ds[i].GetDescription()
        if frmt.upper() == 'VRT':
            if not os.path.isabs(ms_name):
                ms_relative = '1'
                ms_name = os.path.relpath(ms_name, os.path.dirname(out_name))

        vrt_xml += """    <SpectralBand%s>
      <SourceFilename relativeToVRT="%s">%s</SourceFilename>
      <SourceBand>%d</SourceBand>
    </SpectralBand>\n""" % (dstband, ms_relative, ms_name, sband.GetBand())

    vrt_xml += """  </PansharpeningOptions>\n"""
    vrt_xml += """</VRTDataset>\n"""

    if frmt.upper() == 'VRT':
        f = gdal.VSIFOpenL(out_name, 'wb')
        if f is None:
            print('Cannot create %s' % out_name)
            return 1
        gdal.VSIFWriteL(vrt_xml, 1, len(vrt_xml), f)
        gdal.VSIFCloseL(f)
        if verbose_vrt:
            vrt_ds = gdal.Open(out_name, gdal.GA_Update)
            vrt_ds.SetMetadata(vrt_ds.GetMetadata())
        else:
            vrt_ds = gdal.Open(out_name)
        if vrt_ds is None:
            return 1

        return 0

    vrt_ds = gdal.Open(vrt_xml)
    out_ds = gdal.GetDriverByName(frmt).CreateCopy(out_name,
                                                   vrt_ds,
                                                   0,
                                                   creation_options,
                                                   callback=callback)
    if out_ds is None:
        return 1
    return 0
Example #15
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()}
Example #16
0
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
Example #17
0
    if len(projection) > 0:
        t_fh.write('\t<SRS>%s</SRS>\n' % projection)

    if separate:
        band_n = 0
        for fi in file_infos:
            band_n = band_n + 1
            if len(fi.band_types) != 2:
                print ('File %s has %d bands. Only first band will be taken into accout' % (fi.filename, len(fi.band_types)-1))
            dataType = gdal.GetDataTypeName(fi.band_types[1])

            t_fh.write('\t<VRTRasterBand dataType="%s" band="%i">\n'
                % (dataType, band_n))
            t_fh.write('\t\t<ColorInterp>%s</ColorInterp>\n' %
                gdal.GetColorInterpretationName(fi.color_interps[1]))
            fi.write_source(t_fh, geotransform, xsize, ysize, 1)
            t_fh.write('\t</VRTRasterBand>\n')
    else:
        for band in range(1, bands+1):
            dataType = gdal.GetDataTypeName(file_infos[0].band_types[band])

            t_fh.write('\t<VRTRasterBand dataType="%s" band="%i">\n'
                % (dataType, band))
            if file_infos[0].nodata != [None]:
                t_fh.write('\t\t<NoDataValue>%f</NoDataValue>\n' %
                    file_infos[0].nodata[band])
            t_fh.write('\t\t<ColorInterp>%s</ColorInterp>\n' %
                gdal.GetColorInterpretationName(
                    file_infos[0].color_interps[band]))
    def gdal_pansharpen(self, input_string):
        ''' Modified version of gdal_pansharpen.py script 

            Arguments :
            input_string	--	str. 
                                Parameters as defined in the self.Usage() function defined above.

            Returns :
                1	-- If the algorithm failed
                0	-- If the algorithm succeeded (i.e. a new pansharpened image was created)
        '''

        argv = input_string.split(' ')

        if argv is None:
            return -1

        pan_name = None
        last_name = None
        spectral_ds = []
        spectral_bands = []
        out_name = None
        bands = []
        weights = []
        format = 'GTiff'
        creation_options = []
        callback = gdal.TermProgress
        resampling = None
        spat_adjust = None
        verbose_vrt = False
        num_threads = None
        bitdepth = None
        nodata = None

        i = 1
        argc = len(argv)
        while i < argc:
            if argv[i] == '-of' and i < len(argv) - 1:
                format = argv[i + 1]
                i = i + 1
            elif argv[i] == '-r' and i < len(argv) - 1:
                resampling = argv[i + 1]
                i = i + 1
            elif argv[i] == '-spat_adjust' and i < len(argv) - 1:
                spat_adjust = argv[i + 1]
                i = i + 1
            elif argv[i] == '-b' and i < len(argv) - 1:
                bands.append(int(argv[i + 1]))
                i = i + 1
            elif argv[i] == '-w' and i < len(argv) - 1:
                weights.append(float(argv[i + 1]))
                i = i + 1
            elif argv[i] == '-co' and i < len(argv) - 1:
                creation_options.append(argv[i + 1])
                i = i + 1
            elif argv[i] == '-threads' and i < len(argv) - 1:
                num_threads = argv[i + 1]
                i = i + 1
            elif argv[i] == '-bitdepth' and i < len(argv) - 1:
                bitdepth = argv[i + 1]
                i = i + 1
            elif argv[i] == '-nodata' and i < len(argv) - 1:
                nodata = argv[i + 1]
                i = i + 1
            elif argv[i] == '-q':
                callback = None
            elif argv[i] == '-verbose_vrt':
                verbose_vrt = True
            elif argv[i][0] == '-':
                sys.stderr.write('Unrecognized option : %s\n' % argv[i])
                return self.Usage()
            elif pan_name is None:
                pan_name = argv[i]
                pan_ds = gdal.Open(pan_name)
                if pan_ds is None:
                    return 1
            else:
                if last_name is not None:
                    pos = last_name.find(',band=')
                    if pos > 0:
                        spectral_name = last_name[0:pos]
                        ds = gdal.Open(spectral_name)
                        if ds is None:
                            return 1
                        band_num = int(last_name[pos + len(',band='):])
                        band = ds.GetRasterBand(band_num)
                        spectral_ds.append(ds)
                        spectral_bands.append(band)
                    else:
                        spectral_name = last_name
                        ds = gdal.Open(spectral_name)
                        if ds is None:
                            return 1
                        for j in range(ds.RasterCount):
                            spectral_ds.append(ds)
                            spectral_bands.append(ds.GetRasterBand(j + 1))

                last_name = argv[i]

            i = i + 1

        print(
            "Format : {}, Bands : {}, pan_fn : {}, spectral_fn : {}, output_fn : {} "
            .format(format, bands, pan_name, spectral_name, last_name))

        if pan_name is None or len(spectral_bands) == 0:
            return self.Usage()
        out_name = last_name

        if len(bands) == 0:
            bands = [j + 1 for j in range(len(spectral_bands))]
        else:
            for i in range(len(bands)):
                if bands[i] < 0 or bands[i] > len(spectral_bands):
                    print('Invalid band number in -b: %d' % bands[i])
                    return 1

        if len(weights) != 0 and len(weights) != len(spectral_bands):
            print(
                'There must be as many -w values specified as input spectral bands'
            )
            return 1

        vrt_xml = """<VRTDataset subClass="VRTPansharpenedDataset">\n"""
        if bands != [j + 1 for j in range(len(spectral_bands))]:
            for i in range(len(bands)):
                band = spectral_bands[bands[i] - 1]
                datatype = gdal.GetDataTypeName(band.DataType)
                colorname = gdal.GetColorInterpretationName(
                    band.GetColorInterpretation())
                vrt_xml += """  <VRTRasterBand dataType="%s" band="%d" subClass="VRTPansharpenedRasterBand">
          <ColorInterp>%s</ColorInterp>
      </VRTRasterBand>\n""" % (datatype, i + 1, colorname)

        vrt_xml += """  <PansharpeningOptions>\n"""

        if len(weights) != 0:
            vrt_xml += """      <AlgorithmOptions>\n"""
            vrt_xml += """        <Weights>"""
            for i in range(len(weights)):
                if i > 0: vrt_xml += ","
                vrt_xml += "%.16g" % weights[i]
            vrt_xml += "</Weights>\n"
            vrt_xml += """      </AlgorithmOptions>\n"""

        if resampling is not None:
            vrt_xml += '      <Resampling>%s</Resampling>\n' % resampling

        if num_threads is not None:
            vrt_xml += '      <NumThreads>%s</NumThreads>\n' % num_threads

        if bitdepth is not None:
            vrt_xml += '      <BitDepth>%s</BitDepth>\n' % bitdepth

        if nodata is not None:
            vrt_xml += '      <NoData>%s</NoData>\n' % nodata

        if spat_adjust is not None:
            vrt_xml += '      <SpatialExtentAdjustment>%s</SpatialExtentAdjustment>\n' % spat_adjust

        pan_relative = '0'
        if format.upper() == 'VRT':
            if not os.path.isabs(pan_name):
                pan_relative = '1'
                pan_name = os.path.relpath(pan_name, os.path.dirname(out_name))

        vrt_xml += """    <PanchroBand>
          <SourceFilename relativeToVRT="%s">%s</SourceFilename>
          <SourceBand>1</SourceBand>
        </PanchroBand>\n""" % (pan_relative, pan_name)

        for i in range(len(spectral_bands)):
            dstband = ''
            for j in range(len(bands)):
                if i + 1 == bands[j]:
                    dstband = ' dstBand="%d"' % (j + 1)
                    break

            ms_relative = '0'
            ms_name = spectral_ds[i].GetDescription()
            if format.upper() == 'VRT':
                if not os.path.isabs(ms_name):
                    ms_relative = '1'
                    ms_name = os.path.relpath(ms_name,
                                              os.path.dirname(out_name))

            vrt_xml += """    <SpectralBand%s>
          <SourceFilename relativeToVRT="%s">%s</SourceFilename>
          <SourceBand>%d</SourceBand>
        </SpectralBand>\n""" % (dstband, ms_relative, ms_name,
                                spectral_bands[i].GetBand())

        vrt_xml += """  </PansharpeningOptions>\n"""
        vrt_xml += """</VRTDataset>\n"""

        if format.upper() == 'VRT':
            f = gdal.VSIFOpenL(out_name, 'wb')
            if f is None:
                print('Cannot create %s' % out_name)
                return 1
            gdal.VSIFWriteL(vrt_xml, 1, len(vrt_xml), f)
            gdal.VSIFCloseL(f)
            if verbose_vrt:
                vrt_ds = gdal.Open(out_name, gdal.GA_Update)
                vrt_ds.SetMetadata(vrt_ds.GetMetadata())
            else:
                vrt_ds = gdal.Open(out_name)
            if vrt_ds is None:
                return 1

            return 0

        vrt_ds = gdal.Open(vrt_xml)
        out_ds = gdal.GetDriverByName(format).CreateCopy(out_name,
                                                         vrt_ds,
                                                         0,
                                                         creation_options,
                                                         callback=callback)
        if out_ds is None:
            return 1
        return 0
Example #19
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
Example #20
0
def main(argv=sys.argv):
    names = []
    out_file = 'out.vrt'

    ulx = None
    psize_x = None
    separate = False
    # pre_init = None

    argv = gdal.GeneralCmdLineProcessor(argv)
    if argv is None:
        return 0

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

        if arg == '-o':
            i = i + 1
            out_file = argv[i]

        elif arg == '-i':
            i = i + 1
            in_file_list = open(argv[i])
            names.extend(in_file_list.read().split())

        elif arg == '-separate':
            separate = True

        elif arg == '-ul_lr':
            ulx = float(argv[i + 1])
            uly = float(argv[i + 2])
            lrx = float(argv[i + 3])
            lry = float(argv[i + 4])
            i = i + 4

        elif arg[:1] == '-':
            print('Unrecognized command option: ', arg)
            Usage()
            return 1

        else:
            names.append(arg)

        i = i + 1

    if not names:
        print('No input files selected.')
        Usage()
        return 1

    # Collect information on all the source files.
    file_infos = names_to_fileinfos(names)
    if not file_infos:
        print('Nothing to process, exiting.')
        return 1

    if ulx is None:
        ulx = file_infos[0].ulx
        uly = file_infos[0].uly
        lrx = file_infos[0].lrx
        lry = file_infos[0].lry

        for fi in file_infos:
            ulx = min(ulx, fi.ulx)
            uly = max(uly, fi.uly)
            lrx = max(lrx, fi.lrx)
            lry = min(lry, fi.lry)

    if psize_x is None:
        psize_x = file_infos[0].geotransform[1]
        psize_y = file_infos[0].geotransform[5]

    projection = file_infos[0].projection

    for fi in file_infos:
        if fi.geotransform[1] != psize_x or fi.geotransform[5] != psize_y:
            print("All files must have the same scale; %s does not"
                  % fi.filename)
            return 1

        if fi.geotransform[2] != 0 or fi.geotransform[4] != 0:
            print("No file must be rotated; %s is" % fi.filename)
            return 1

        if fi.projection != projection:
            print("All files must be in the same projection; %s is not"
                  % fi.filename)
            return 1

    geotransform = (ulx, psize_x, 0.0, uly, 0.0, psize_y)

    xsize = int(((lrx - ulx) / geotransform[1]) + 0.5)
    ysize = int(((lry - uly) / geotransform[5]) + 0.5)

    if separate:
        bands = len(file_infos)
    else:
        bands = file_infos[0].bands

    t_fh = open(out_file, 'w')
    t_fh.write('<VRTDataset rasterXSize="%i" rasterYSize="%i">\n'
               % (xsize, ysize))
    t_fh.write('\t<GeoTransform>%24.16f, %24.16f, %24.16f, %24.16f, %24.16f, %24.16f</GeoTransform>\n'
               % geotransform)

    if projection:
        t_fh.write('\t<SRS>%s</SRS>\n' % projection)

    if separate:
        band_n = 0
        for fi in file_infos:
            band_n = band_n + 1
            if len(fi.band_types) != 2:
                print('File %s has %d bands. Only first band will be taken '
                      'into account' % (fi.filename, len(fi.band_types) - 1))
            dataType = gdal.GetDataTypeName(fi.band_types[1])

            t_fh.write('\t<VRTRasterBand dataType="%s" band="%i">\n'
                       % (dataType, band_n))
            t_fh.write('\t\t<ColorInterp>%s</ColorInterp>\n' %
                       gdal.GetColorInterpretationName(fi.color_interps[1]))
            fi.write_source(t_fh, geotransform, xsize, ysize, 1)
            t_fh.write('\t</VRTRasterBand>\n')
    else:
        for band in range(1, bands + 1):
            dataType = gdal.GetDataTypeName(file_infos[0].band_types[band])

            t_fh.write('\t<VRTRasterBand dataType="%s" band="%i">\n'
                       % (dataType, band))
            if file_infos[0].nodata != [None]:
                t_fh.write('\t\t<NoDataValue>%f</NoDataValue>\n' %
                           file_infos[0].nodata[band])
            t_fh.write('\t\t<ColorInterp>%s</ColorInterp>\n' %
                       gdal.GetColorInterpretationName(
                           file_infos[0].color_interps[band]))

            ct = file_infos[0].cts[band]
            if ct is not None:
                t_fh.write('\t\t<ColorTable>\n')
                for i in range(ct.GetCount()):
                    t_fh.write(
                        '\t\t\t<Entry c1="%i" c2="%i" c3="%i" c4="%i"/>\n'
                        % ct.GetColorEntry(i))
                t_fh.write('\t\t</ColorTable>\n')

            for fi in file_infos:
                fi.write_source(t_fh, geotransform, xsize, ysize, band)

            t_fh.write('\t</VRTRasterBand>\n')

    t_fh.write('</VRTDataset>\n')

    return 0
Example #21
0
def main(argv=None):

    bReportHistograms = False
    bApproxStats = False
    scale = 1.0
    offset = 0.0
    bComputeMinMax = False
    bStats = False
    bScale = False
    pszFilename = None

    if argv is None:
        argv = sys.argv

    argv = gdal.GeneralCmdLineProcessor(argv)

    if argv is None:
        return 1

    nArgc = len(argv)
    #/* -------------------------------------------------------------------- */
    #/*      Parse arguments.                                                */
    #/* -------------------------------------------------------------------- */
    i = 1
    while i < nArgc:

        if EQUAL(argv[i], "--utility_version"):
            print(("%s is running against GDAL %s" %
                   (argv[0], gdal.VersionInfo("RELEASE_NAME"))))
            return 0
        elif EQUAL(argv[i], "-mm"):
            bComputeMinMax = True
        elif EQUAL(argv[i], "-unscale"):
            bScale = True
        elif EQUAL(argv[i], "-stats"):
            bStats = True
        elif EQUAL(argv[i], "-hist"):
            bReportHistograms = True
        elif argv[i][0] == '-':
            return Usage()
        elif pszFilename is None:
            pszFilename = argv[i]
        else:
            return Usage()

        i = i + 1

    if pszFilename is None:
        return Usage()
    if not (bComputeMinMax or bScale or bStats or bReportHistograms):
        return Usage()

#/* -------------------------------------------------------------------- */
#/*      Open dataset.                                                   */
#/* -------------------------------------------------------------------- */
    hDataset = gdal.Open(pszFilename, gdal.GA_ReadOnly)

    if hDataset is None:
        print(("gdalinfo failed - unable to open '%s'." % pszFilename))
        return 1


#/* ==================================================================== */
#/*      Loop over bands.                                                */
#/* ==================================================================== */
    for iBand in range(hDataset.RasterCount):
        hBand = hDataset.GetRasterBand(iBand + 1)
        (nBlockXSize, nBlockYSize) = hBand.GetBlockSize()

        if bScale:
            offset = hBand.GetOffset()
            if offset is None:
                offset = 0.0
            scale = hBand.GetScale()
            if scale is None:
                scale = 1.0

        if (hDataset.RasterCount > 1):
            print(( "Band %d Block=%dx%d Type=%s, ColorInterp=%s" % ( iBand+1, \
                 nBlockXSize, nBlockYSize, \
                 gdal.GetDataTypeName(hBand.DataType), \
                 gdal.GetColorInterpretationName( \
                 hBand.GetRasterColorInterpretation()) )))

        dfMin = hBand.GetMinimum()
        dfMax = hBand.GetMaximum()
        if dfMin is not None or dfMax is not None or bComputeMinMax:

            line = ""
            if dfMin is not None:
                dfMin = (dfMin * scale) + offset
                line = line + ("Min=%.3f " % (dfMin))
            if dfMax is not None:
                dfMax = (dfMax * scale) + offset
                line = line + ("Max=%.3f " % (dfMax))

            if bComputeMinMax:
                gdal.ErrorReset()
                adfCMinMax = hBand.ComputeRasterMinMax(True)
                if gdal.GetLastErrorType() == gdal.CE_None:
                    line = line + ( "  Computed Min/Max=%.3f,%.3f" % ( \
                            ((adfCMinMax[0] * scale) + offset), \
                            ((adfCMinMax[1] * scale) + offset) ))
                    print(line)

            #if bStats:
            #   print( line )

        stats = hBand.GetStatistics(bApproxStats, bStats)
        #inType = gdal.GetDataTypeName(hBand.DataType)

        # Dirty hack to recognize if stats are valid. If invalid, the returned
        # stddev is negative
        if stats[3] >= 0.0:
            if bStats:
                mean = (stats[2] * scale) + offset
                stdev = (stats[3] * scale) + offset
                rms = math.sqrt((mean * mean) + (stdev * stdev))
                print(( "Min=%.2f, Max=%.2f, Mean=%.2f, StdDev=%.2f, RMS=%.2f" \
                  % ((stats[0] * scale) + offset, (stats[1] * scale) + offset,\
                     mean, stdev, rms )))

        if bReportHistograms:
            print("level\tvalue\tcount\tcumulative")

            #Histogram call not returning exact min and max.
            #...Workaround run gdalinfo -stats and then use min/max from above

            hist = hBand.GetDefaultHistogram(force=True)
            #hist = hBand.GetDefaultHistogram(force = True, callback = gdal.TermProgress)
            cnt = 0
            sum = 0
            sumTotal = 0
            if hist is not None:
                #use dfMin and dfMax from previous calls when possible
                if dfMin is None:
                    dfMin = (hist[0] * scale) + offset
                if dfMax is None:
                    dfMax = (hist[1] * scale) + offset
                nBucketCount = hist[2]
                panHistogram = hist[3]

                #print( "  %d buckets from %g to %g:" % ( \
                #        nBucketCount, dfMin, dfMax ))
                #print ( "scale: %g, offset: %g" % (scale, offset))
                #increment = round(((dfMax - dfMin) / nBucketCount),2)
                increment = (dfMax - dfMin) / nBucketCount
                value = dfMin
                #get total to normalize (below)
                for bucket in panHistogram:
                    sumTotal = sumTotal + bucket
                for bucket in panHistogram:
                    sum = sum + bucket
                    #normalize cumulative
                    nsum = sum / float(sumTotal)
                    line = "%d\t%0.2f\t%d\t%0.6f" % (cnt, value, bucket, nsum)
                    print(line)
                    cnt = cnt + 1
                    value = value + increment

    return True
Example #22
0
def Preprocess(argv):
    names = []
    out_file = 'out.vrt'

    ulx = None
    psize_x = None
    separate = False
    pre_init = None
    a_srs = None
    a_nodata = None

    if argv is None:
        sys.exit(0)

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

        if arg == '-o':
            i = i + 1
            out_file = argv[i]

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

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

        elif arg == '-ul_lr':
            ulx = float(argv[i + 1])
            uly = float(argv[i + 2])
            lrx = float(argv[i + 3])
            lry = float(argv[i + 4])
            i = i + 4

        elif arg[:1] == '-':
            print 'Unrecognised command option: ', arg
            Usage()
            sys.exit(1)

        else:
            names.append(arg)

        i = i + 1

    if len(names) == 0:
        print 'No input files selected.'
        Usage()
        sys.exit(1)

    # Collect information on all the source files.
    file_infos = names_to_fileinfos(names)

    if ulx is None:
        ulx = file_infos[0].ulx
        uly = file_infos[0].uly
        lrx = file_infos[0].lrx
        lry = file_infos[0].lry

        for fi in file_infos:
            ulx = min(ulx, fi.ulx)
            uly = max(uly, fi.uly)
            lrx = max(lrx, fi.lrx)
            lry = min(lry, fi.lry)

    if psize_x is None:
        psize_x = file_infos[0].geotransform[1]
        psize_y = file_infos[0].geotransform[5]

    projection = file_infos[0].projection

    for fi in file_infos:
        pass
        # MAPTILER COMMENT
        #if fi.geotransform[1] != psize_x or fi.geotransform[5] != psize_y:
        #	print "All files must have the same scale; %s does not" \
        #		% fi.filename
        #	sys.exit(1)

        # MAPTILER COMMENT
        #if fi.geotransform[2] != 0 or fi.geotransform[4] != 0:
        #	print "No file must be rotated/skewed; %s is.\nTODO: gdalwarp -of vrt %s %s.vrt" % (fi.filename, fi.filename, fi.filename)
        #	sys.exit(1)

        #TODO: During initialization create temporary files by AutoCreateWarpedVRT for those

        #if fi.projection != projection:
        #	print "All files must be in the same projection; %s is not" \
        #		% fi.filename
        #	sys.exit(1)

    # MAPTILER COMMENT
    #geotransform = (ulx, psize_x, 0.0, uly, 0.0, psize_y)
    geotransform = file_infos[0].geotransform

    gcpprojection = file_infos[0].gcpprojection
    gcps = file_infos[0].gcps

    xsize = int(((lrx - ulx) / geotransform[1]) + 0.5)
    ysize = int(((lry - uly) / geotransform[5]) + 0.5)

    nodata = None
    if a_nodata:
        if a_nodata.find(',') != -1:
            nodata = a_nodata.split(',')
        elif a_nodata.find(' ') != -1:
            nodata = a_nodata.split(' ')
        else:
            nodata = [a_nodata] * 5  # bands + 1
        nodata = map(int, nodata)

    palette = False
    bands = file_infos[0].bands
    if file_infos[0].palette:
        palette = True
        if not (nodata or file_infos[0].nodata != [None]):
            # Palette without NODATA is expanded also to an extra alpha channel
            bands = 4
        else:
            # Palette with NODATA
            bands = 3
    palettecolors = ['Red', 'Green', 'Blue', 'Alpha']

    if a_srs:
        srs = osr.SpatialReference()
        srs.SetFromUserInput(a_srs)
        projection = srs.ExportToWkt()

    t_fh = open(out_file, 'w')

    t_fh.write('<VRTDataset rasterXSize="%i" rasterYSize="%i">\n' %
               (xsize, ysize))

    # Datasets with GCPs can't be merged without warping in advance!!!
    if len(gcps):
        t_fh.write('\t<GCPList Projection="%s">\n' %
                   gdal.EscapeString(gcpprojection, gdal.CPLES_XML))
        for gcp in gcps:
            t_fh.write(
                '\t\t<GCP Id="%s" Pixel="%.4f" Line="%.4f" X="%f" Y="%f"/>\n' %
                (gcp.Id, gcp.GCPPixel, gcp.GCPLine, gcp.GCPX, gcp.GCPY))
        t_fh.write('\t</GCPList>\n')
    else:
        t_fh.write(
            '\t<GeoTransform>%24.13f, %24.13f, %24.13f, %24.13f, %24.13f, %24.13f</GeoTransform>\n'
            % geotransform)

        if len(projection) > 0:
            t_fh.write('\t<SRS>%s</SRS>\n' %
                       gdal.EscapeString(projection, gdal.CPLES_XML))

    if nodata:
        nd = nodata
        t_fh.write(
            '\t<Metadata>\n\t\t<MDI key="NODATA_VALUES">%i %i %i</MDI>\n\t</Metadata>\n'
            % (nd[0], nd[1], nd[2]))
    if file_infos[0].nodata != [None]:
        nd = file_infos[0].nodata
        t_fh.write(
            '\t<Metadata>\n\t\t<MDI key="NODATA_VALUES">%i %i %i</MDI>\n\t</Metadata>\n'
            % (nd[0], nd[1], nd[2]))

    for band in range(1, bands + 1):
        dataType = "Byte"
        # gdal.GetDataTypeName(file_infos[0].band_types[band])

        t_fh.write('\t<VRTRasterBand dataType="%s" band="%i">\n' %
                   (dataType, band))

        if nodata:
            t_fh.write('\t\t<NoDataValue>%f</NoDataValue>\n' % nodata[band])
        elif file_infos[0].nodata != [None]:
            t_fh.write('\t\t<NoDataValue>%f</NoDataValue>\n' %
                       file_infos[0].nodata[band])
        if palette:
            t_fh.write('\t\t<ColorInterp>%s</ColorInterp>\n' %
                       palettecolors[band - 1])
        else:
            t_fh.write('\t\t<ColorInterp>%s</ColorInterp>\n' %
                       gdal.GetColorInterpretationName(
                           file_infos[0].color_interps[band]))

        for fi in file_infos:
            fi.write_source(t_fh, geotransform, xsize, ysize, band, nodata)

        t_fh.write('\t</VRTRasterBand>\n')

    t_fh.write('</VRTDataset>\n')
Example #23
0
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 _get_gdal_metadata(self, filename):
        # let's do GDAL here ? if it fails do Hachoir
        from osgeo import gdal, osr, gdalconst
        ds = gdal.Open(filename, gdal.GA_ReadOnly)

        # TODO: get bounding box
        geotransform = ds.GetGeoTransform()
        projref = ds.GetProjectionRef()
        if not projref:
            # default to WGS84
            projref = osr.GetWellKnownGeogCSAsWKT('EPSG:4326')
        spref = osr.SpatialReference(projref)  # SRS
        # extract bbox
        #       see http://svn.osgeo.org/gdal/trunk/gdal/swig/python/samples/gdalinfo.py
        #       GDALInfoReportCorner
        # bbox = left,bottom,right,top
        # bbox = min Longitude , min Latitude , max Longitude , max Latitude
        # bbox in srs units
        # transform points into georeferenced coordinates
        left, top = self._geotransform(0.0, 0.0, geotransform)
        right, bottom = self._geotransform(ds.RasterXSize, ds.RasterYSize,
                                           geotransform)
        # transform points to dataset projection coordinates
        if not spref.IsLocal():
            # TODO: check whether it really is not possible to transform local coordinate systems
            spref_latlon = spref.CloneGeogCS()
            trans = osr.CoordinateTransformation(spref_latlon, spref)
            left, top, _ = trans.TransformPoint(left, top, 0)
            right, bottom, _ = trans.TransformPoint(right, bottom, 0)
            srs = '{0}:{1}'.format(
                spref.GetAuthorityName(
                    None),  # 'PROJCS', 'GEOGCS', 'GEOGCS|UNIT', None
                spref.GetAuthorityCode(None))
        else:
            srs = None
        # build metadata struct
        data = {
            'size': (ds.RasterXSize, ds.RasterYSize),
            'bands': ds.RasterCount,
            'projection': projref,  # WKT
            'srs': srs,
            'origin': (geotransform[0], geotransform[3]),
            'Pxiel Size': (geotransform[1], geotransform[5]),
            'bounds': {
                'left': left,
                'bottom': bottom,
                'right': right,
                'top': top
            }
        }
        data.update(ds.GetMetadata_Dict())
        data.update(ds.GetMetadata_Dict('EXIF'))
        from libxmp.core import XMPMeta
        xmp = ds.GetMetadata('xml:XMP') or []
        if xmp:
            data['xmp'] = {}
        for xmpentry in xmp:
            xmpmd = XMPMeta()
            xmpmd.parse_from_str(xmpentry)
            for xmpitem in self._traverseXMP(xmpmd):
                (schema, name, value, options) = xmpitem
                if options['IS_SCHEMA']:
                    continue
                if options['ARRAY_IS_ALT']:
                    # pick first element and move on
                    data['xmp'][name] = xmpmd.get_array_item(schema, name, 1)
                    continue
                # current item

                # ARRAY_IS_ALT .. ARRAY_IS_ALT_TEXT, pick first one (value is array + array is ordered)

                # -> array elements don't have special markers :(

                if options['ARRAY_IS_ALT']:
                    pass
                if options['HAS_LANG']:
                    pass
                if options['VALUE_IS_STRUCT']:
                    pass
                if options['ARRAY_IS_ALTTEXT']:
                    pass
                if options['VALUE_IS_ARRAY']:
                    pass
                if options['ARRAY_IS_ORDERED']:
                    pass

                #     -> ALT ARRAY_VALUE???
                # if options['VALUE_IS_ARRAY']:

                # else:
                data['xmp'][name] = value

        # EXIF could provide at least:
        #   width, height, bistpersample, compression, planarconfiguration,
        #   sampleformat, xmp-metadata (already parsed)

        # TODO: get driver metadata?
        #     ds.GetDriver().getMetadata()
        #     ds.GetDriver().ds.GetMetadataItem(gdal.DMD_XXX)

        # Extract GDAL metadata
        for numband in range(1, ds.RasterCount + 1):
            band = ds.GetRasterBand(numband)
            (min_, max_, mean, stddev) = band.ComputeStatistics(False)
            banddata = {
                'data type':
                gdal.GetDataTypeName(band.DataType),
                # band.GetRasterColorTable().GetCount() ... color table with
                # count entries
                'min':
                min_,
                'max':
                max_,
                'mean':
                mean,
                'stddev':
                stddev,
                'color interpretation':
                gdal.GetColorInterpretationName(band.GetColorInterpretation()),
                'description':
                band.GetDescription(),
                'nodata':
                band.GetNoDataValue(),
                'size': (band.XSize, band.YSize),
                'index':
                band.GetBand(),
                #band.GetCategoryNames(), GetRasterCategoryNames() .. ?
                #band.GetScale()
            }
            banddata.update(band.GetMetadata())
            if not 'band' in data:
                data['band'] = []
            data['band'].append(banddata)

            # extract Raster Attribute table (if any)
            rat = band.GetDefaultRAT()

            def _getColValue(rat, row, col):
                valtype = rat.GetTypeOfCol(col)
                if valtype == gdalconst.GFT_Integer:
                    return rat.GetValueAsInt(row, col)
                if valtype == gdalconst.GFT_Real:
                    return rat.GetValueAsDouble(row, col)
                if valtype == gdalconst.GFT_String:
                    return rat.GetValueAsString(row, col)
                return None

            GFU_MAP = {
                gdalconst.GFU_Generic: 'Generic',
                gdalconst.GFU_Max: 'Max',
                gdalconst.GFU_MaxCount: 'MaxCount',
                gdalconst.GFU_Min: 'Min',
                gdalconst.GFU_MinMax: 'MinMax',
                gdalconst.GFU_Name: 'Name',
                gdalconst.GFU_PixelCount: 'PixelCount',
                gdalconst.GFU_Red: 'Red',
                gdalconst.GFU_Green: 'Green',
                gdalconst.GFU_Blue: 'Blue',
                gdalconst.GFU_Alpha: 'Alpha',
                gdalconst.GFU_RedMin: 'RedMin',
                gdalconst.GFU_GreenMin: 'GreenMin',
                gdalconst.GFU_BlueMin: 'BlueMin',
                gdalconst.GFU_AlphaMax: 'AlphaMin',
                gdalconst.GFU_RedMax: 'RedMax',
                gdalconst.GFU_GreenMax: 'GreenMax',
                gdalconst.GFU_BlueMin: 'BlueMax',
                gdalconst.GFU_AlphaMax: 'AlphaMax',
            }

            GFT_MAP = {
                gdalconst.GFT_Integer: 'Integer',
                gdalconst.GFT_Real: 'Real',
                gdalconst.GFT_String: 'String',
            }

            if rat:
                banddata['rat'] = {
                    'rows': [[
                        _getColValue(rat, rowidx, colidx)
                        for colidx in range(0, rat.GetColumnCount())
                    ] for rowidx in range(0, rat.GetRowCount())],
                    'cols': [{
                        'name': rat.GetNameOfCol(idx),
                        'type': GFT_MAP[rat.GetTypeOfCol(idx)],
                        'usage': GFU_MAP[rat.GetUsageOfCol(idx)],
                        'idx': idx
                    } for idx in range(0, rat.GetColumnCount())],
                }
                # Assume if there is a RAT we have categorical data
                banddata['type'] = 'categorical'
            else:
                banddata['type'] = 'continuous'

        ds = None

        # HACHOIR Tif extractor:
        # ret = {}
        # for field in parser:
        #     if field.name.startswith('ifd'):
        #         data = {
        #           'img_height': field['img_height']['value'].value,
        #           'img_width': field['img_width']['value'].value,
        #           'bits_per_sample': field['bits_per_sample']['value'].value,
        #           'compression': field['compression']['value'].display
        #         }
        #         ret = data
        return data
Example #25
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
Example #26
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
Example #27
0
def gdal_pansharpen(argv: Optional[Sequence[str]] = None,
                    pan_name: Optional[str] = None,
                    spectral_names: Optional[Sequence[str]] = None,
                    spectral_ds: Optional[List[gdal.Dataset]] = None,
                    spectral_bands: Optional[List[gdal.Band]] = None,
                    band_nums: Optional[Sequence[int]] = None,
                    weights: Optional[Sequence[float]] = None,
                    dst_filename: Optional[str] = None,
                    driver_name: Optional[str] = None,
                    creation_options: Optional[Sequence[str]] = None,
                    resampling: Optional[str] = None,
                    spat_adjust: Optional[str] = None,
                    num_threads: Optional[Union[int, str]] = None,
                    bitdepth: Optional[Union[int, str]] = None,
                    nodata_value: Optional[Union[Real, str]] = None,
                    verbose_vrt: bool = False,
                    progress_callback: Optional = gdal.TermProgress_nocb):
    if argv:
        # this is here for backwards compatibility
        return main(argv)

    spectral_names = spectral_names or []
    spectral_ds = spectral_ds or []
    spectral_bands = spectral_bands or []
    band_nums = band_nums or []
    weights = weights or []
    creation_options = creation_options or []

    if spectral_names:
        parse_spectral_names(spectral_names=spectral_names,
                             spectral_ds=spectral_ds,
                             spectral_bands=spectral_bands)

    if pan_name is None or not spectral_bands:
        return 1

    pan_ds = gdal.Open(pan_name)
    if pan_ds is None:
        return 1

    if driver_name is None:
        driver_name = GetOutputDriverFor(dst_filename)

    if not band_nums:
        band_nums = [j + 1 for j in range(len(spectral_bands))]
    else:
        for band in band_nums:
            if band < 0 or band > len(spectral_bands):
                print('Invalid band number in -b: %d' % band)
                return 1

    if weights and len(weights) != len(spectral_bands):
        print(
            'There must be as many -w values specified as input spectral bands'
        )
        return 1

    vrt_xml = """<VRTDataset subClass="VRTPansharpenedDataset">\n"""
    if band_nums != [j + 1 for j in range(len(spectral_bands))]:
        for i, band in enumerate(band_nums):
            sband = spectral_bands[band - 1]
            datatype = gdal.GetDataTypeName(sband.DataType)
            colorname = gdal.GetColorInterpretationName(
                sband.GetColorInterpretation())
            vrt_xml += """  <VRTRasterBand dataType="%s" band="%d" subClass="VRTPansharpenedRasterBand">
      <ColorInterp>%s</ColorInterp>
  </VRTRasterBand>\n""" % (datatype, i + 1, colorname)

    vrt_xml += """  <PansharpeningOptions>\n"""

    if weights:
        vrt_xml += """      <AlgorithmOptions>\n"""
        vrt_xml += """        <Weights>"""
        for i, weight in enumerate(weights):
            if i > 0:
                vrt_xml += ","
            vrt_xml += "%.16g" % weight
        vrt_xml += "</Weights>\n"
        vrt_xml += """      </AlgorithmOptions>\n"""

    if resampling is not None:
        vrt_xml += f'      <Resampling>{resampling}</Resampling>\n'

    if num_threads is not None:
        vrt_xml += f'      <NumThreads>{num_threads}</NumThreads>\n'

    if bitdepth is not None:
        vrt_xml += f'      <BitDepth>{bitdepth}</BitDepth>\n'

    if nodata_value is not None:
        vrt_xml += f'      <NoData>{nodata_value}</NoData>\n'

    if spat_adjust is not None:
        vrt_xml += f'      <SpatialExtentAdjustment>{spat_adjust}</SpatialExtentAdjustment>\n'

    pan_relative = '0'
    if driver_name.upper() == 'VRT':
        if not os.path.isabs(pan_name):
            pan_relative = '1'
            pan_name = os.path.relpath(pan_name, os.path.dirname(dst_filename))

    vrt_xml += """    <PanchroBand>
      <SourceFilename relativeToVRT="%s">%s</SourceFilename>
      <SourceBand>1</SourceBand>
    </PanchroBand>\n""" % (pan_relative, pan_name)

    for i, sband in enumerate(spectral_bands):
        dstband = ''
        for j, band in enumerate(band_nums):
            if i + 1 == band:
                dstband = ' dstBand="%d"' % (j + 1)
                break

        ms_relative = '0'
        ms_name = spectral_ds[i].GetDescription()
        if driver_name.upper() == 'VRT':
            if not os.path.isabs(ms_name):
                ms_relative = '1'
                ms_name = os.path.relpath(ms_name,
                                          os.path.dirname(dst_filename))

        vrt_xml += """    <SpectralBand%s>
      <SourceFilename relativeToVRT="%s">%s</SourceFilename>
      <SourceBand>%d</SourceBand>
    </SpectralBand>\n""" % (dstband, ms_relative, ms_name, sband.GetBand())

    vrt_xml += """  </PansharpeningOptions>\n"""
    vrt_xml += """</VRTDataset>\n"""

    if driver_name.upper() == 'VRT':
        f = gdal.VSIFOpenL(dst_filename, 'wb')
        if f is None:
            print('Cannot create %s' % dst_filename)
            return 1
        gdal.VSIFWriteL(vrt_xml, 1, len(vrt_xml), f)
        gdal.VSIFCloseL(f)
        if verbose_vrt:
            vrt_ds = gdal.Open(dst_filename, gdal.GA_Update)
            vrt_ds.SetMetadata(vrt_ds.GetMetadata())
        else:
            vrt_ds = gdal.Open(dst_filename)
        if vrt_ds is None:
            return 1

        return 0

    vrt_ds = gdal.Open(vrt_xml)
    out_ds = gdal.GetDriverByName(driver_name).CreateCopy(
        dst_filename, vrt_ds, 0, creation_options, callback=progress_callback)
    if out_ds is None:
        return 1
    return 0
Example #28
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
Example #29
0
    def get_fields_range_type(self):
        """
        Returns the range type fields from a gdal dataset
        :rtype: list[GDALField]
        """
        import osgeo.gdal as gdal

        fields = []
        for i in range(1, self.gdal_dataset.RasterCount + 1):
            band = self.gdal_dataset.GetRasterBand(i)

            # Get the field name
            if band.GetColorInterpretation():
                field_name = gdal.GetColorInterpretationName(
                    band.GetColorInterpretation())
            else:
                field_name = ConfigManager.default_field_name_prefix + str(i)

            nil_value = str(band.GetNoDataValue()) if band.GetNoDataValue(
            ) is not None else ""
            # Check if the nil value is an integer and if it is float then split it to 2 integers (e.g: -10.4 -> [-11:-10] as rasdaman does not support floating null values
            # TODO: Remove this check once rasdaman supports floating null values
            is_number = False
            if nil_value != "nan" and nil_value != "":
                # if string is not nan or "", so just consider it is a float number
                nil_value = float(nil_value)
                is_number = True

            if is_number:
                floor_nill_value = int(math.floor(float(nil_value)))
                ceil_nill_value = int(math.ceil(float(nil_value)))

                if ceil_nill_value > 9223372036854775807 or floor_nill_value < -9223372036854775808:
                    log.info(
                        "\033[1mThe nodata value {} of band {} has been ignored "
                        "as it cannot be represented as a 64 bit integer.".
                        format(nil_value, field_name))
                    nil_value = None
                else:
                    if floor_nill_value == ceil_nill_value:
                        nil_value = str(floor_nill_value)
                    else:
                        # NOTE: There is no nilValues interval e.g: 0:200 in Rasdaman, everything has to be separated, such as: 0,200
                        nil_value = str(floor_nill_value) + "," + str(
                            ceil_nill_value)
            else:
                # Band does not contain any nodata_value, then check if nullvalue is specified in ingredient file
                dfn = ConfigManager.default_null_values
                if len(dfn) > i - 1:
                    nil_value = str(dfn[i - 1])

            if nil_value is None:
                nil_values = [None]
            else:
                nil_values = nil_value.strip().split(",")

            # Get the unit of measure
            uom = band.GetUnitType() if band.GetUnitType(
            ) else ConfigManager.default_unit_of_measure

            # Add it to the list of fields
            fields.append(GDALField(field_name, uom, nil_values))

        return fields