Example #1
0
def getBoundingBoxFromIsisLabel(filePath):
    '''Function to read the bounding box from an ISIS label file'''

    if not os.path.exists(filePath):
        raise Exception('Error, missing label file path!')

    numFound = 0
    f = open(filePath, 'r')
    for line in f:
        if ('MINIMUM_LATITUDE' in line) or ('MinimumLatitude' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<')
            if (endPos >= 0):
                minLat = float(s[:endPos - 1])
            else:
                minLat = float(s)
            numFound = numFound + 1
            continue
        if ('MAXIMUM_LATITUDE' in line) or ('MaximumLatitude' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<')
            if (endPos >= 0):
                maxLat = float(s[:endPos - 1])
            else:
                maxLat = float(s)
            numFound = numFound + 1
            continue
        if ('EASTERNMOST_LONGITUDE'
                in line) or ('MAXIMUM_LONGITUDE'
                             in line) or ('MaximumLongitude' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<')  # Check for unit name
            if (endPos >= 0):
                maxLon = float(s[:endPos - 1])
            else:
                maxLon = float(s)
            numFound = numFound + 1
            continue
        if ('WESTERNMOST_LONGITUDE'
                in line) or ('MINIMUM_LONGITUDE'
                             in line) or ('MinimumLongitude' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<')  # Check for unit name
            if (endPos >= 0):
                minLon = float(s[:endPos - 1])
            else:
                minLon = float(s)
            numFound = numFound + 1
            continue
        if numFound == 4:
            break

    f.close()
    if numFound < 4:
        raise Exception('Failed to find lat/lon bounds in file ' + filePath)

    return (minLon, maxLon, minLat, maxLat)
Example #2
0
def getProjectedBoundsFromIsisLabel(filePath):
    '''Function to read the projected coordinates bounding box from an ISIS label file'''

    if not os.path.exists(filePath):
        raise Exception('Error, missing label file path!')

    # Read all the values!
    minX = None
    maxY = None
    pixRes = None
    numRows = None
    numCols = None
    f = open(filePath, 'r')
    for line in f:
        if ('UpperLeftCornerX' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<')
            if (endPos >= 0):
                minX = float(s[:endPos - 1])
            else:
                minX = float(s)
            continue
        if ('UpperLeftCornerY' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<')
            if (endPos >= 0):
                maxY = float(s[:endPos - 1])
            else:
                maxY = float(s)
            continue
        if ('PixelResolution' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<')
            if (endPos >= 0):
                pixRes = float(s[:endPos - 1])
            else:
                pixRes = float(s)
            continue
        if ('      Samples =' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            numCols = float(s)
            continue
        if ('      Lines   =' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            numRows = float(s)
            continue

    f.close()
    if (not minX) or (not maxY) or (not pixRes) or (not numRows) or (
            not numCols):
        raise Exception('Failed to find projected bounds in file ' + filePath)

    # Compute the other bounds
    maxX = minX + pixRes * numCols
    minY = maxY - pixRes * numRows

    return (minX, maxX, minY, maxY)
Example #3
0
def getProjectedBoundsFromIsisLabel(filePath):
    '''Function to read the projected coordinates bounding box from an ISIS label file'''

    if not os.path.exists(filePath):
        raise Exception('Error, missing label file path!')
    
    # Read all the values!
    minX    = None
    maxY    = None
    pixRes  = None
    numRows = None
    numCols = None
    f = open(filePath, 'r')
    for line in f:
        if ('UpperLeftCornerX' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<')
            if (endPos >= 0):
                minX = float(s[:endPos-1])
            else:
                minX = float(s)
            continue
        if ('UpperLeftCornerY' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<')
            if (endPos >= 0):
                maxY = float(s[:endPos-1])
            else:
                maxY = float(s)
            continue
        if ('PixelResolution' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<')
            if (endPos >= 0):
                pixRes = float(s[:endPos-1])
            else:
                pixRes = float(s)
            continue
        if ('      Samples =' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            numCols = float(s)
            continue
        if ('      Lines   =' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            numRows = float(s)
            continue
        
    f.close()
    if (not minX) or (not maxY) or (not pixRes) or (not numRows) or (not numCols):
        raise Exception('Failed to find projected bounds in file ' + filePath)

    # Compute the other bounds
    maxX = minX + pixRes*numCols
    minY = maxY - pixRes*numRows

    return (minX, maxX, minY, maxY)
Example #4
0
def getBoundingBoxFromIsisLabel(filePath):
    '''Function to read the bounding box from an ISIS label file'''

    if not os.path.exists(filePath):
        raise Exception('Error, missing label file path!')
    
    numFound = 0
    f = open(filePath, 'r')
    for line in f:
        if ('MINIMUM_LATITUDE' in line) or ('MinimumLatitude' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<')
            if (endPos >= 0):
                minLat = float(s[:endPos-1])
            else:
                minLat = float(s)
            numFound = numFound + 1
            continue
        if ('MAXIMUM_LATITUDE' in line) or ('MaximumLatitude' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<')
            if (endPos >= 0):
                maxLat = float(s[:endPos-1])
            else:
                maxLat = float(s)
            numFound = numFound + 1
            continue
        if ('EASTERNMOST_LONGITUDE' in line) or ('MAXIMUM_LONGITUDE' in line)  or ('MaximumLongitude' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<') # Check for unit name
            if (endPos >= 0):
                maxLon = float(s[:endPos-1])
            else:
                maxLon = float(s)
            numFound = numFound + 1
            continue
        if ('WESTERNMOST_LONGITUDE' in line) or ('MINIMUM_LONGITUDE' in line) or ('MinimumLongitude' in line):
            s = asp_string_utils.getLineAfterText(line, '=')
            endPos = s.find('<') # Check for unit name
            if (endPos >= 0):
                minLon = float(s[:endPos-1])
            else:
                minLon = float(s)
            numFound = numFound + 1
            continue
        if numFound == 4:
            break

    f.close()
    if numFound < 4:
        raise Exception('Failed to find lat/lon bounds in file ' + filePath)

    return (minLon, maxLon, minLat, maxLat)
Example #5
0
def getGdalInfoTagValue(text, tag):
    """Gets the value of a gdal parameter in a [""] tag or None if it is absent."""

    try:
        lineAfterTag = asp_string_utils.getLineAfterText(text, tag)
        
        # The remaining line should look like this: ",25],
        commaPos   = lineAfterTag.find(',')
        bracketPos = lineAfterTag.find(']')
        # The value is always returned as a string
        return asp_string_utils.convertToFloatIfNumber(lineAfterTag[commaPos+1:bracketPos])
    
    except Exception: # Requested tag was not found
        return None
Example #6
0
def getGdalInfoTagValue(text, tag):
    """Gets the value of a gdal parameter in a [""] tag or None if it is absent."""

    try:
        lineAfterTag = asp_string_utils.getLineAfterText(text, tag)
        
        # The remaining line should look like this: ",25],
        commaPos   = lineAfterTag.find(',')
        bracketPos = lineAfterTag.find(']')
        # The value is always returned as a string
        return asp_string_utils.convertToFloatIfNumber(lineAfterTag[commaPos+1:bracketPos])
    
    except Exception: # Requested tag was not found
        return None
Example #7
0
def getProjectionFromIsisLabel(filePath):
    '''Function to read the projection type from an ISIS label file'''

    if not os.path.exists(filePath):
        raise Exception('Error, missing label file path!')
    
    f = open(filePath, 'r')
    for line in f:
        if ('MAP_PROJECTION_TYPE          =' in line) or ('ProjectionName     =' in line):
            line = line.replace('"','') # Strip quotes
            projType = asp_string_utils.getLineAfterText(line, '=').strip()
            f.close()
            return projType
    f.close()
    raise Exception('Unable to find projection type in file ' + filePath)
Example #8
0
def getProjectionFromIsisLabel(filePath):
    '''Function to read the projection type from an ISIS label file'''

    if not os.path.exists(filePath):
        raise Exception('Error, missing label file path!')
    
    f = open(filePath, 'r')
    for line in f:
        if ('MAP_PROJECTION_TYPE          =' in line) or ('ProjectionName     =' in line):
            line = line.replace('"','') # Strip quotes
            projType = asp_string_utils.getLineAfterText(line, '=').strip()
            f.close()
            return projType
    f.close()
    raise Exception('Unable to find projection type in file ' + filePath)
Example #9
0
def getImageGeoInfo(imagePath, getStats=True):
    """Obtains some image geo information from gdalinfo in dictionary format"""
    
    if not os.path.exists(imagePath):
        raise Exception('Error: input file ' + imagePath + ' does not exist!')
    
    outputDict = {}
    
    # Call command line tool silently
    cmd = [asp_system_utils.which('gdalinfo'), imagePath, '-proj4']
    if getStats:
        cmd.append('-stats')
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
    textOutput, err = p.communicate()
    
    # Get the size in pixels
    imageSizeLine = asp_string_utils.getLineAfterText(textOutput, 'Size is ')
    sizeVals      = imageSizeLine.split(',')
    outputDict['image_size'] = (int(sizeVals[0]), int(sizeVals[1]))

    # Get origin location and pixel size    
    originLine    = asp_string_utils.getLineAfterText(textOutput, 'Origin = ')
    pixelSizeLine = asp_string_utils.getLineAfterText(textOutput, 'Pixel Size = ')    
    originVals    = asp_string_utils.getNumbersInParentheses(originLine)
    pixelSizeVals = asp_string_utils.getNumbersInParentheses(pixelSizeLine)
    outputDict['origin']     = originVals
    outputDict['pixel_size'] = pixelSizeVals

    # Get bounding box in projected coordinates
    upperLeftLine  = asp_string_utils.getLineAfterText(textOutput, 'Upper Left')
    lowerRightLine = asp_string_utils.getLineAfterText(textOutput, 'Lower Right')
    (minX, maxY)   = asp_string_utils.getNumbersInParentheses(upperLeftLine)
    (maxX, minY)   = asp_string_utils.getNumbersInParentheses(lowerRightLine)
    outputDict['projection_bounds'] = (minX, maxX, minY, maxY)
    outputDict['projection_center'] = ( (minX+maxX)/2.0, (minY+maxY)/2.0 )

    # Get some proj4 values
    outputDict['standard_parallel_1'] = getGdalInfoTagValue(textOutput, 'standard_parallel_1')
    outputDict['central_meridian']    = getGdalInfoTagValue(textOutput, 'central_meridian')

    # Get the projection type
    projStart = textOutput.find('PROJ.4 string is:')
    nextLine  = textOutput.find("'", projStart)+1
    endLine   = textOutput.find("'", nextLine)
    outputDict['proj_string'] = textOutput[nextLine:endLine]
    outputDict['projection'] = 'UNKNOWN'
    if '+proj=eqc' in textOutput:
        outputDict['projection'] = 'EQUIRECTANGULAR'
    elif '+proj=ster' in textOutput:
        outputDict['projection'] = 'POLAR STEREOGRAPHIC'
    
    # Extract this variable which ASP inserts into its point cloud files
    try:
        pointOffsetLine = asp_string_utils.getLineAfterText(textOutput, 'POINT_OFFSET=') # Tag name must be synced with C++ code
        offsetValues    = pointOffsetLine.split(' ')
        outputDict['point_offset'] =  (float(offsetValues[0]), float(offsetValues[1]), float(offsetValues[2]))        
    except:
        pass # In most cases this line will not be present

    # TODO: Currently this does not find much information, and there
    #       is another function in image_utils dedicated to returning statistics.
    if getStats:

        # List of dictionaries per band
        outputDict['band_info'] = []
    
        # Populate band information
        band = 1
        while (True): # Loop until we run out of bands
            bandString = 'Band ' + str(band) + ' Block='
            bandLoc = textOutput.find(bandString)
            if bandLoc < 0: # Ran out of bands
                break
        
            # Found the band, read pertinent information
            bandInfo = {}
        
            # Get the type string
            bandLine = asp_string_utils.getLineAfterText(textOutput, bandString)
            typePos  = bandLine.find('Type=')
            commaPos = bandLine.find(',')
            typeName = bandLine[typePos+5:commaPos-1]
            bandInfo['type'] = typeName
        
            outputDict['band_info'] = bandInfo
        
            band = band + 1 # Move on to the next band
        
    return outputDict
Example #10
0
def getImageGeoInfo(imagePath, getStats=True):
    """Obtains some image geo information from gdalinfo in dictionary format"""
    
    if not os.path.exists(imagePath):
        raise Exception('Error: input file ' + imagePath + ' does not exist!')
    
    outputDict = {}
    
    # Call command line tool silently
    cmd = [asp_system_utils.which('gdalinfo'), imagePath, '-proj4']
    if getStats:
        cmd.append('-stats')
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
    textOutput, err = p.communicate()
    
    # Get the size in pixels
    imageSizeLine = asp_string_utils.getLineAfterText(textOutput, 'Size is ')
    sizeVals      = imageSizeLine.split(',')
    outputDict['image_size'] = (int(sizeVals[0]), int(sizeVals[1]))

    # Get origin location and pixel size    
    originLine    = asp_string_utils.getLineAfterText(textOutput, 'Origin = ')
    pixelSizeLine = asp_string_utils.getLineAfterText(textOutput, 'Pixel Size = ')    
    originVals    = asp_string_utils.getNumbersInParentheses(originLine)
    pixelSizeVals = asp_string_utils.getNumbersInParentheses(pixelSizeLine)
    outputDict['origin']     = originVals
    outputDict['pixel_size'] = pixelSizeVals

    # Get bounding box in projected coordinates
    upperLeftLine  = asp_string_utils.getLineAfterText(textOutput, 'Upper Left')
    lowerRightLine = asp_string_utils.getLineAfterText(textOutput, 'Lower Right')
    (minX, maxY)   = asp_string_utils.getNumbersInParentheses(upperLeftLine)
    (maxX, minY)   = asp_string_utils.getNumbersInParentheses(lowerRightLine)
    outputDict['projection_bounds'] = (minX, maxX, minY, maxY)
    outputDict['projection_center'] = ( (minX+maxX)/2.0, (minY+maxY)/2.0 )

    # Get some proj4 values
    outputDict['standard_parallel_1'] = getGdalInfoTagValue(textOutput, 'standard_parallel_1')
    outputDict['central_meridian']    = getGdalInfoTagValue(textOutput, 'central_meridian')

    # Get the projection type
    projStart = textOutput.find('PROJ.4 string is:')
    nextLine  = textOutput.find("'", projStart)+1
    endLine   = textOutput.find("'", nextLine)
    outputDict['proj_string'] = textOutput[nextLine:endLine]
    outputDict['projection'] = 'UNKNOWN'
    if '+proj=eqc' in textOutput:
        outputDict['projection'] = 'EQUIRECTANGULAR'
    elif ('+proj=ster' in textOutput) or ('+proj=stere' in textOutput):
        outputDict['projection'] = 'POLAR STEREOGRAPHIC'

    outputDict['lonlat_bounds'] = outputDict['projection_bounds']
    if '+proj=longlat' not in outputDict['proj_string']:
        longlatString = getLonLatProjString(outputDict['proj_string'])
        ul = convertCoordinate(outputDict['proj_string'], longlatString, minX, maxY)
        br = convertCoordinate(outputDict['proj_string'], longlatString, maxX, minY)
        outputDict['lonlat_bounds'] = (ul[0], br[0], br[1], ul[1])

    # Extract this variable which ASP inserts into its point cloud files
    try:
        pointOffsetLine = asp_string_utils.getLineAfterText(textOutput, 'POINT_OFFSET=') # Tag name must be synced with C++ code
        offsetValues    = pointOffsetLine.split(' ')
        outputDict['point_offset'] =  (float(offsetValues[0]), float(offsetValues[1]), float(offsetValues[2]))        
    except:
        pass # In most cases this line will not be present

    # TODO: Currently this does not find much information, and there
    #       is another function in image_utils dedicated to returning statistics.
    if getStats:

        # List of dictionaries per band
        outputDict['band_info'] = []
    
        # Populate band information
        band = 1
        while (True): # Loop until we run out of bands
            bandString = 'Band ' + str(band) + ' Block='
            bandLoc = textOutput.find(bandString)
            if bandLoc < 0: # Ran out of bands
                break
        
            # Found the band, read pertinent information
            bandInfo = {}
        
            # Get the type string
            bandLine = asp_string_utils.getLineAfterText(textOutput, bandString)
            typePos  = bandLine.find('Type=')
            commaPos = bandLine.find(',')
            typeName = bandLine[typePos+5:commaPos-1]
            bandInfo['type'] = typeName
        
            outputDict['band_info'] = bandInfo
        
            band = band + 1 # Move on to the next band
        
    return outputDict