def get_utm_wkt(coordinate, from_wkt): ''' Function to return CRS for UTM zone of specified coordinates. Used to transform coords to metres @param coordinate: single coordinate pair ''' def utm_getZone(longitude): return (int(1 + (longitude + 180.0) / 6.0)) def utm_isNorthern(latitude): if (latitude < 0.0): return 0 else: return 1 coordinate_array = np.array(coordinate).reshape((1, 2)) latlon_coord_trans = get_coordinate_transformation(from_wkt, 'EPSG:4326') latlon_coord = coordinate if latlon_coord_trans is None else latlon_coord_trans.TransformPoints( coordinate_array)[0][0:2] # Set UTM coordinate reference system utm_spatial_ref = SpatialReference() utm_spatial_ref.SetWellKnownGeogCS('WGS84') utm_spatial_ref.SetUTM(utm_getZone(latlon_coord[0]), utm_isNorthern(latlon_coord[1])) return utm_spatial_ref.ExportToWkt()
def alt_downloader(tile_nr_x, tile_nr_y): # construct url url = www_folder + str(tile_nr_x) + '/' + str(tile_nr_y) + '.asc.zip' try: # create a momemory driver and dataset on it driver = gdal.GetDriverByName('MEM') ds = driver.Create('', TD['NCOLS'], TD['NROWS'], 1, gdal.GDT_Float32) # access the zip file zf = ZipFile(BytesIO(requests.get(url).content)) # read the rasterfile in the format of an array lines = zf.open(zf.infolist()[0]).readlines() # NOTE: # in the following lines we use some properties that the .asc files on our server have: # - carriage returns are used to separate header items and rows # - the header is 6 lines, that is, there is a NO DATA value in line 6 # - the data starts in line 7 (index 6) # these are not required by the standard, c.f. # http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/ESRI_ASCII_raster_format/009t0000000z000000/ # in particular, NO DATA is optional and carriage returns may be replaced by spaces # read the geo transform #as from http://geoexamples.blogspot.com/2012/01/creating-files-in-ogr-and-gdal-with.html: #geotransform = (left x-coordinate, x-cellsize, rotation ?,upper y-coordinate,rotation,y-cellsize) #Xgeo = geotransform[0] + Xpixel*geotransform[1] + Yline*geotransform[2] #Ygeo = geotransform[3] + Xpixel*geotransform[4] + Yline*geotransform[5] #for some reason, y-cellsize must be negative here geo_trafo = (float(lines[2].split()[1]), TD['CELLSIZE'], 0, float(lines[3].split()[1]) + TD['CELLSIZE'] * TD['NROWS'], 0, -TD['CELLSIZE']) ds.SetGeoTransform(geo_trafo) # read and write the data to the dataset arr = list(map(lambda x: list(map(float, x.split())), lines[6:])) zf.close() band = ds.GetRasterBand(1) band.WriteArray(array(arr)) # set the spatial reference system (probably not necessary) proj = SpatialReference() proj.SetWellKnownGeogCS("EPSG:31287") ds.SetProjection(proj.ExportToWkt()) return ds except: return None
def __init__(self, filename=FILENAME): print(f"[INFO] Reading geofile from '{filename}'") self.dataset = gdal.Open(filename, gdal.GA_ReadOnly) self.geotransform = self.dataset.GetGeoTransform() self.band = self.dataset.GetRasterBand(1) srcRef = SpatialReference() srcRef.SetWellKnownGeogCS("WGS84") dstRef = SpatialReference(self.dataset.GetProjection()) self.ct = CoordinateTransformation(srcRef, dstRef) gdalVersion = osgeo.gdal.__version__ print(f"[INFO] Using gdal ver. {gdalVersion}") self.gdalMajorVer = int(gdalVersion[:gdalVersion.find('.')])
def get_spatial_ref_from_wkt(wkt_or_crs_name): ''' Function to return SpatialReference object for supplied WKT @param wkt: Well-known text or CRS name for SpatialReference, including "EPSG:XXXX" @return spatial_ref: SpatialReference from WKT ''' spatial_ref = SpatialReference() # Try to resolve WKT result = spatial_ref.ImportFromWkt(wkt_or_crs_name) if not result: return spatial_ref # Try to resolve CRS name - either mapped or original result = spatial_ref.SetWellKnownGeogCS( CRS_NAME_MAPPING.get(wkt_or_crs_name) or wkt_or_crs_name) if not result: return spatial_ref # Try common formulations for UTM zones #TODO: Fix this so it works in the Northern hemisphere modified_crs_name = re.sub('\s+', '', wkt_or_crs_name.strip().upper()) utm_match = (re.match('(\w+)/MGAZONE(\d+)', modified_crs_name) or re.match('(\w+)/(\d+)S', modified_crs_name) or re.match('(EPSG:283)(\d{2})', modified_crs_name)) if utm_match: modified_crs_name = utm_match.group(1) utm_zone = int(utm_match.group(2)) result = spatial_ref.SetWellKnownGeogCS( CRS_NAME_MAPPING.get(modified_crs_name) or modified_crs_name) if not result: spatial_ref.SetUTM( utm_zone, False ) # Put this here to avoid potential side effects in downstream code return spatial_ref assert not result, 'Invalid WKT or CRS name'
def get_spatial_ref_from_wkt(wkt_or_crs_name): ''' Function to return SpatialReference object for supplied WKT @param wkt: Well-known text or CRS name for SpatialReference, including "EPSG:XXXX" @return spatial_ref: SpatialReference from WKT ''' if not wkt_or_crs_name: return None spatial_ref = SpatialReference() result = spatial_ref.SetFromUserInput(wkt_or_crs_name) if not result: logger.debug( 'CRS determined using SpatialReference.SetFromUserInput({})'. format(wkt_or_crs_name)) return spatial_ref # Try to resolve WKT result = spatial_ref.ImportFromWkt(wkt_or_crs_name) if not result: logger.debug( 'CRS determined using SpatialReference.ImportFromWkt({})'.format( wkt_or_crs_name)) return spatial_ref # Try to resolve CRS name - either mapped or original modified_crs_name = CRS_NAME_MAPPING.get( wkt_or_crs_name) or wkt_or_crs_name result = spatial_ref.SetWellKnownGeogCS(modified_crs_name) if not result: logger.debug( 'CRS determined using SpatialReference.SetWellKnownGeogCS({})'. format(modified_crs_name)) return spatial_ref match = re.match('EPSG:(\d+)$', wkt_or_crs_name, re.IGNORECASE) if match: epsg_code = int(match.group(1)) result = spatial_ref.ImportFromEPSG(epsg_code) if not result: logger.debug( 'CRS determined using SpatialReference.ImportFromEPSG({})'. format(epsg_code)) return spatial_ref # Try common formulations for UTM zones #TODO: Fix this so it works in the Northern hemisphere modified_crs_name = re.sub('\s+', '', wkt_or_crs_name.strip().upper()) utm_match = (re.match('(\w+)/MGAZONE(\d+)$', modified_crs_name) or re.match('(\w+)/(\d+)S$', modified_crs_name) or re.match('(EPSG:283)(\d{2})$', modified_crs_name) or re.match('(MGA)(\d{2}$)', modified_crs_name)) if utm_match: modified_crs_name = utm_match.group(1) modified_crs_name = CRS_NAME_MAPPING.get( modified_crs_name) or modified_crs_name utm_zone = int(utm_match.group(2)) result = spatial_ref.SetWellKnownGeogCS(modified_crs_name) if not result: spatial_ref.SetUTM( utm_zone, False ) # Put this here to avoid potential side effects in downstream code logger.debug( 'UTM CRS determined using SpatialReference.SetWellKnownGeogCS({}) (zone{})' .format(modified_crs_name, utm_zone)) return spatial_ref assert not result, 'Invalid WKT or CRS name: "{}"'.format(wkt_or_crs_name)