def __init__(self, shapefile_path): #Load resources for coordinate transformations epsg27700 = SpatialReference() epsg27700.ImportFromEPSG(27700) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) self.bng2latlon = CoordinateTransformation(epsg27700, epsg4326) self.latlon2bng = CoordinateTransformation(epsg4326, epsg27700) #Load shapefile r = sfl.Reader(shapefile_path) shapes = r.shapes() #calculate representive coordines for eah point by averaging the bounding box corners bboxes = [s.bbox for s in shapes] x_coords = [b[0] for b in bboxes] + [b[2] for b in bboxes] y_coords = [b[1] for b in bboxes] + [b[3] for b in bboxes] self.high_x = np.max(x_coords) self.high_y = np.max(y_coords) self.low_x = np.min(x_coords) self.low_y = np.min(y_coords) # print "Upper boundary:",self.high_x, self.high_y # print "Lower boundary:", self.low_x, self.low_y self.rep_coords = [((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0) for b in bboxes] self.records = r.records() self.shapely_shapes = [Polygon(shape.points) for shape in shapes]
def toWGS84(x, y): epsg28992 = SpatialReference() epsg28992.ImportFromEPSG(28992) epsg28992.SetTOWGS84(565.237, 50.0087, 465.658, -0.406857, 0.350733, -1.87035, 4.0812) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) rd2latlon = CoordinateTransformation(epsg28992, epsg4326) latlon2rd = CoordinateTransformation(epsg4326, epsg28992) latlonz = rd2latlon.TransformPoint(x, y) return latlonz
def testClipReproject(self): # Build the test file. imageFile = self._createTestFile() # Build the envelope. ulx = 367080 uly = 4209230 lrx = 509200 lry = 4095100 srs = SpatialReference() srs.ImportFromEPSG(32612) env = Envelope() env.addPoint(ulx, uly, 0, srs) env.addPoint(lrx, lry, 0, srs) # Reprojection parameter targetSRS = SpatialReference() targetSRS.ImportFromEPSG(4326) # Clip, reproject and resample. imageFile.clipReproject(env, targetSRS,) # Check the results. dataset = gdal.Open(imageFile.fileName(), gdalconst.GA_ReadOnly) if not dataset: raise RuntimeError('Unable to read ' + imageFile.fileName() + '.') xform = dataset.GetGeoTransform() xScale = xform[1] yScale = xform[5] width = dataset.RasterXSize height = dataset.RasterYSize clippedUlx = xform[0] clippedUly = xform[3] clippedLrx = clippedUlx + width * xScale clippedLry = clippedUly + height * yScale self.assertAlmostEqual(clippedUlx, -112.49369402670872, places=12) self.assertAlmostEqual(clippedUly, 38.03073206024332, places=11) self.assertAlmostEqual(clippedLrx, -110.89516946364738, places=12) self.assertAlmostEqual(clippedLry, 36.99265291293727, places=11) outSRS = SpatialReference() outSRS.ImportFromWkt(dataset.GetProjection()) self.assertTrue(outSRS.IsSame(targetSRS)) # Delete the test file. os.remove(imageFile.fileName())
def geographic2plane(eo, epsg): # Define the Plane Coordinate System (EPSG 5186) plane = SpatialReference() plane.ImportFromEPSG(epsg) # Define the wgs84 system (EPSG 4326) geographic = SpatialReference() geographic.ImportFromEPSG(4326) coord_transformation = CoordinateTransformation(geographic, plane) # Check the transformation for a point close to the centre of the projected grid xy = coord_transformation.TransformPoint(float(eo[0]), float( eo[1])) # The order: Lon, Lat return xy[0:2]
def coord_conv(epsg_from,epsg_to,cord_xlong,cord_ylat): # if epsg_from and epsg_to : epsgfrom = SpatialReference() epsgfrom.ImportFromEPSG(epsg_from) epsgto = SpatialReference() epsgto.ImportFromEPSG(epsg_to) # Check for Projection exists if not epsgfrom.GetAttrValue("PROJCS|AUTHORITY", 1): cord_xlong=ddmmss_to_dd(cord_xlong) cord_ylat=ddmmss_to_dd(cord_ylat) psd2_IsProjected=False if epsgto.GetAttrValue("PROJCS|AUTHORITY", 1): psd2_IsProjected=True # Datum_epsg_from = epsgfrom.GetAttrValue("PROJCS|GEOGCS|AUTHORITY", 1) Datum_epsg_from = epsgfrom.GetAttrValue("GEOGCS|AUTHORITY", 1) Datum_epsg_to = epsgto.GetAttrValue("GEOGCS|AUTHORITY", 1) if int(Datum_epsg_from) == 4229: epsgfrom.SetTOWGS84(-121.8,98.1,-10.7,0,0,0.554,-0.2263) if int(Datum_epsg_to) == 4229: epsgto.SetTOWGS84(-121.8,98.1,-10.7,0,0,0.554,-0.2263) # ---------------------------- if psd2_IsProjected: FromTo_psd = CoordinateTransformation(epsgfrom, epsgto) x_to,y_to,zcart_to = FromTo_psd.TransformPoint(cord_xlong, cord_ylat) x_to = format(round(x_to,2),'.2f') y_to = format(round(y_to,2),'.2f') else: x_to,y_to,zcart_to=None,None,None # -------- Case Projected To Get the datum from info of epsg2 and calculate lat/long------------------------ epsgto.ImportFromEPSG(int(Datum_epsg_to)) if int(Datum_epsg_to) == 4229: epsgto.SetTOWGS84(-121.8,98.1,-10.7,0,0,0.554,-0.2263) FromTo_psd = CoordinateTransformation(epsgfrom, epsgto) long_to,lat_to,zcart2_to = FromTo_psd.TransformPoint(cord_xlong, cord_ylat) lat_to = ddmmss_to_dms(dd_to_ddmmss(lat_to)) + " N" long_to = ddmmss_to_dms(dd_to_ddmmss(long_to)) + " E" return (x_to,y_to,zcart_to,long_to,lat_to,zcart2_to)
def gdal_reproject( cls, src: Union[str, gdal.Dataset], output_file: str = None, # The filepath of the output image to write to. src_srs: osr.SpatialReference = None, dst_srs: osr.SpatialReference = None, # Defaults to epsg if None epsg: int = None, error_threshold: float = 0.125, resampling: gdalconst = gdalconst.GRA_NearestNeighbour ) -> Optional["GDALGrid"]: """ Reproject a raster image. """ src_ds = cls.load_raster(src)[0] if dst_srs is None: dst_srs = osr.SpatialReference() dst_srs.ImportFromEPSG(int(epsg)) dst_wkt = dst_srs.ExportToWkt() if not isinstance(resampling, int): resampling = getattr(gdal, resampling) src_wkt = None if src_srs is not None: src_wkt = src_srs.ExportToWkt() reprojected_ds = gdal.AutoCreateWarpedVRT(src_ds, src_wkt, dst_wkt, resampling, error_threshold) if output_file: gdal.GetDriverByName('GTiff').CreateCopy(output_file, reprojected_ds) return GDALGrid(reprojected_ds)
def testExpandByPercentage(self): ulx = 374187 uly = 4202663 lrx = 501598 lry = 4100640 srs = SpatialReference() srs.ImportFromEPSG(32612) env = Envelope() env.addPoint(ulx, uly, 0, srs) env.addPoint(lrx, lry, 0, srs) env.expandByPercentage(0.0) self.assertEqual(ulx, env.ulx()) self.assertEqual(uly, env.uly()) self.assertEqual(lrx, env.lrx()) self.assertEqual(lry, env.lry()) percentage = 10 width = 127411.0 height = 163224.55529116935 exWidth = width * percentage / 100 / 2.0 exHeight = height * percentage / 100 / 2.0 exUlx = abs(ulx - exWidth) exUly = abs(uly + exHeight) newUlx, newUly, newLrx, newLry = env.expandByPercentage(percentage) self.assertEqual(exUlx, newUlx) self.assertEqual(exUly, newUly)
def testConsistentResults(self): ulx = 94.2 uly = 19.4 lrx = 94.6 lry = 19.1 srs = SpatialReference() srs.ImportFromEPSG(4326) srs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER) env = Envelope() env.addPoint(ulx, uly, 0, srs) env.addPoint(lrx, lry, 0, srs) fpq = FootprintsQuery(FootprintsQueryTestCase._logger) fpq.addAoI(env) numScenes = 27 fpq.setMaximumScenes(numScenes) fpScenes1 = fpq.getScenes() fpScenes2 = fpq.getScenes() self.assertEqual(len(fpScenes1), numScenes) self.assertEqual(len(fpScenes1), len(fpScenes2)) for i in range(len(fpScenes1)): self.assertEqual(fpScenes1[i].fileName(), fpScenes2[i].fileName())
def envelope(self): dataset = self.getDataset() xform = dataset.GetGeoTransform() xScale = xform[1] yScale = xform[5] width = dataset.RasterXSize height = dataset.RasterYSize ulx = xform[0] uly = xform[3] lrx = ulx + width * xScale lry = uly + height * yScale envelope = Envelope() # --- # If this file is in 4326, we must swap the x-y to conform with GDAL # 3's strict conformity to the 4326 definition. # --- srs4326 = SpatialReference() srs4326.ImportFromEPSG(4326) if srs4326.IsSame(self._dataset.GetSpatialRef()): envelope.addPoint(uly, ulx, 0, self._dataset.GetSpatialRef()) envelope.addPoint(lry, lrx, 0, self._dataset.GetSpatialRef()) else: envelope.addPoint(ulx, uly, 0, self._dataset.GetSpatialRef()) envelope.addPoint(lrx, lry, 0, self._dataset.GetSpatialRef()) return envelope
def tmcentral2latlon(eo): # Define the TM central coordinate system (EPSG 5186) epsg5186 = SpatialReference() epsg5186.ImportFromEPSG(5186) # Define the wgs84 system (EPSG 4326) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) tm2latlon = CoordinateTransformation(epsg5186, epsg4326) # Check the transformation for a point close to the centre of the projected grid lonlat = tm2latlon.TransformPoint(float(eo[0]), float(eo[1])) # The order: x, y eo[0:2] = lonlat[0:2] return eo
def plane2geographic(xy, epsg=32610): # Define the Plane Coordinate System (e.g. 5186) plane = SpatialReference() plane.ImportFromEPSG(epsg) # Define the wgs84 system (EPSG 4326) geographic = SpatialReference() geographic.ImportFromEPSG(4326) coord_transformation = CoordinateTransformation(plane, geographic) # Check the transformation for a point close to the centre of the projected grid latlon = coord_transformation.TransformPoint(float(xy[0]), float( xy[1])) # The order: x, y return latlon[:2]
def reproj_convert_layer(geojson_path, output_path, file_format, output_crs, input_crs="epsg:4326"): layer_name = output_path.split('/') layer_name = layer_name[len(layer_name) - 1].split('.')[0] in_driver = GetDriverByName("GeoJSON") out_driver = GetDriverByName(file_format) inSpRef = SpatialReference() inSpRef.ImportFromEPSG(int(input_crs.split("epsg:")[1])) outSpRef = SpatialReference() ret_val = outSpRef.ImportFromProj4(output_crs) if not ret_val == 0: raise ValueError("Error when importing the output crs") coords_transform = CoordinateTransformation(inSpRef, outSpRef) f_in = in_driver.Open(geojson_path) input_layer = f_in.GetLayer() f_out = out_driver.CreateDataSource(output_path) output_layer = f_out.CreateLayer(layer_name, outSpRef) input_lyr_defn = input_layer.GetLayerDefn() for i in range(input_lyr_defn.GetFieldCount()): fieldDefn = input_lyr_defn.GetFieldDefn(i) output_layer.CreateField(fieldDefn) output_lyr_defn = output_layer.GetLayerDefn() for inFeature in input_layer: geom = inFeature.GetGeometryRef() outFeature = OgrFeature(output_lyr_defn) if geom: geom.Transform(coords_transform) outFeature.SetGeometry(geom) else: outFeature.SetGeometry(None) for i in range(output_lyr_defn.GetFieldCount()): outFeature.SetField( output_lyr_defn.GetFieldDefn(i).GetNameRef(), inFeature.GetField(i)) output_layer.CreateFeature(outFeature) outFeature.Destroy() inFeature.Destroy() f_in.Destroy() f_out.Destroy() if "Shapefile" in file_format: outSpRef.MorphToESRI() with open(output_path.replace(".shp", ".prj"), 'w') as file_proj: file_proj.write(outSpRef.ExportToWkt()) with open(output_path.replace(".shp", ".cpg"), "w") as encoding_file: encoding_file.write("ISO-8859-1") return 0
def _extractVars(files, variables, envelope, outDir): srs = SpatialReference() srs.ImportFromEPSG(4326) srs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER) subFiles = [] for f in files: geoFile = GeospatialImageFile(f, spatialReference=srs) subs = geoFile.getDataset().GetSubDatasets() foundVariables = [] # Look for a variable name in the subdataset name. for sub in subs: datasetName = sub[0] var = datasetName.split(':')[2] if var in variables: foundVariables.append(var) # --- # Copy the original file before operating on it, unless # it already exists in the output directory. # --- name = os.path.basename(os.path.splitext(f)[0]) + \ '_' + \ var + \ '.nc' workingCopy = os.path.join(outDir, name) if not os.path.exists(workingCopy): shutil.copyfile(f, workingCopy) # Extract and clip the subdataset. copyGeoFile = GeospatialImageFile(workingCopy, srs) copyGeoFile.clipReproject(envelope, None, sub[0]) else: copyGeoFile = GeospatialImageFile(workingCopy, srs) subFiles.append(copyGeoFile.fileName()) # Stop, when all variables are found. if len(foundVariables) == len(variables): break # Are any variables missing? if len(foundVariables) != len(variables): missing = [v for v in variables if v not in foundVariables] msg = 'Variables not found in ' + str(f) + ': ' + str(missing) raise RuntimeError(msg) return subFiles
def latlon2tmcentral(eo): # Define the TM central coordinate system (EPSG 5186) epsg5186 = SpatialReference() epsg5186.ImportFromEPSG(5186) # Define the wgs84 system (EPSG 4326) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) latlon2tm = CoordinateTransformation(epsg4326, epsg5186) # Check the transformation for a point close to the centre of the projected grid xy = latlon2tm.TransformPoint(float(eo[0]), float(eo[1])) # The order: Lon, Lat eo[0:2] = xy[0:2] return eo
def __init__(self,*args,**kwds): self.ocgis = ocgis(self) sr = kwds.pop('sr',None) if sr is None: sr = SpatialReference() sr.ImportFromEPSG(4326) self.ocgis._proj4_str = sr.ExportToProj4() super(SelectionGeometry,self).__init__(*args,**kwds)
def testSRS(self): testSRS = SpatialReference() testSRS.ImportFromEPSG(32612) obs = ObservationFile(ObservationFileTestCase._testObsFile, ObservationFileTestCase._species) self.assertTrue(obs.srs().IsSame(testSRS))
def convertCoordinateSystem(eo): # Define the TM central coordinate system (EPSG 5186) epsg5186 = SpatialReference() epsg5186.ImportFromEPSG(5186) # Define the wgs84 system (EPSG 4326) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) tm2latlon = CoordinateTransformation(epsg5186, epsg4326) latlon2tm = CoordinateTransformation(epsg4326, epsg5186) # Check the transformation for a point close to the centre of the projected grid xy = latlon2tm.TransformPoint(float(eo[0]), float(eo[1])) converted_eo = copy(eo) converted_eo[0:2] = xy[0:2] return converted_eo
def initcc(self): """ initialize coordinate conversion """ if not hasattr(self, 'rd2latlon'): from osgeo.osr import SpatialReference, CoordinateTransformation # Define the Rijksdriehoek projection system (EPSG 28992) epsg28992 = SpatialReference() epsg28992.ImportFromEPSG(28992) # correct the towgs84 epsg28992.SetTOWGS84(565.237, 50.0087, 465.658, -0.406857, 0.350733, -1.87035, 4.0812) # Define the wgs84 system (EPSG 4326) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) self.rd2latlon = CoordinateTransformation(epsg28992, epsg4326)
def _createTestFile(self, createUTM=False): # --- # Set up a logger because serialization was causing loggers to point # to the SpatialReferences. # --- logger = logging.getLogger() logger.setLevel(logging.INFO) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.INFO) logger.addHandler(ch) testFile = None if createUTM: testFile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'gsenm_250m_eucl_dist_streams.tif') workingCopy = tempfile.mkstemp(suffix='.tif')[1] shutil.copyfile(testFile, workingCopy) srs = SpatialReference() srs.ImportFromEPSG(32612) else: testFile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'TSURF.nc') workingCopy = tempfile.mkstemp(suffix='.nc')[1] shutil.copyfile(testFile, workingCopy) # --- # https://github.com/OSGeo/gdal/blob/release/3.0/gdal/ # MIGRATION_GUIDE.TXT # --- srs = SpatialReference() srs.ImportFromEPSG(4326) srs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER) return GeospatialImageFile(workingCopy, spatialReference=srs, logger=logger)
def srs(self): srs = self._dataset.GetSpatialRef() if not srs: srs = SpatialReference() srs.ImportFromEPSG(4326) srs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER) return srs
def _createTestFile(self): testFile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'TSURF.nc') workingCopy = tempfile.mkstemp(suffix='.nc')[1] shutil.copyfile(testFile, workingCopy) srs = SpatialReference() srs.ImportFromEPSG(4326) return GeospatialImageFile(workingCopy, srs)
def wgs84To28992(lo, la): # Define the Rijksdriehoek projection system (EPSG 28992) epsg28992 = SpatialReference() epsg28992.ImportFromEPSG(28992) # correct the towgs84 epsg28992.SetTOWGS84(565.237, 50.0087, 465.658, -0.406857, 0.350733, -1.87035, 4.0812) # Define the wgs84 system (EPSG 4326) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) rd2latlon = CoordinateTransformation(epsg28992, epsg4326) latlon2rd = CoordinateTransformation(epsg4326, epsg28992) # Check the transformation for a point close to the centre of the projected grid xy = latlon2rd.TransformPoint(lo, la) return ([xy[0], xy[1]])
def getListofMerraImages(self, files): # Convert the list of NetCDF files to GeospatialImageFiles list = [] tgt_srs = SpatialReference() tgt_srs.ImportFromEPSG(4326) for file in files: list.append( GeospatialImageFile(os.path.join(self._merraDir, file), tgt_srs)) return list
def convert_ogr_to_geojson(file_path, file_format): regex_field_name = re.compile("[^a-zA-Z0-9_-ëêàáâãæêéèñòóô]+") in_driver = GetDriverByName(file_format) out_driver = GetDriverByName('MEMORY') f_in = in_driver.Open(file_path) input_layer = f_in.GetLayer() outSpRef = SpatialReference() outSpRef.ImportFromEPSG(4326) coords_transform = CoordinateTransformation(input_layer.GetSpatialRef(), outSpRef) f_out = out_driver.CreateDataSource('') output_layer = f_out.CreateLayer('', outSpRef) input_lyr_defn = input_layer.GetLayerDefn() for i in range(input_lyr_defn.GetFieldCount()): fieldDefn = input_lyr_defn.GetFieldDefn(i) fieldDefn.SetName(regex_field_name.sub('_', fieldDefn.GetNameRef())) output_layer.CreateField(fieldDefn) output_lyr_defn = output_layer.GetLayerDefn() nb_field = output_lyr_defn.GetFieldCount() field_names = [ output_lyr_defn.GetFieldDefn(i).GetNameRef() for i in range(nb_field) ] res = [] for inFeature in input_layer: geom = inFeature.GetGeometryRef() outFeature = OgrFeature(output_lyr_defn) # Don't try to transform empty geometry : if geom: geom.Transform(coords_transform) outFeature.SetGeometry(geom) else: outFeature.SetGeometry(None) outFeature.SetFID(inFeature.GetFID()) for i in range(output_lyr_defn.GetFieldCount()): outFeature.SetField(field_names[i], inFeature.GetField(i)) res.append(outFeature.ExportToJson()) outFeature.Destroy() inFeature.Destroy() f_in.Destroy() f_out.Destroy() return ''.join([ '''{"type":"FeatureCollection","features":[''', ','.join(res), ''']}''' ]).encode()
def testSrs(self): # Build the test file. imageFile = self._createTestFile() # Check the srs. expectedSRS = SpatialReference() expectedSRS.ImportFromEPSG(4326) self.assertTrue(imageFile.srs().IsSame(expectedSRS)) # Delete the test file. os.remove(imageFile.fileName())
def testEnvelope(self): testEnv = Envelope() srs = SpatialReference() srs.ImportFromEPSG(32612) testEnv.addPoint(374187, 4202663, 0, srs) testEnv.addPoint(501598, 4100640, 0, srs) obs = ObservationFile(ObservationFileTestCase._testObsFile, ObservationFileTestCase._species) self.assertTrue(testEnv.Equals(obs.envelope()))
def coord_conv(epsg_from, epsg_to, cord_xlong, cord_ylat): # if epsg_from and epsg_to: epsgfrom = SpatialReference() epsgfrom.ImportFromEPSG(epsg_from) if epsg_from != 4326: epsgfrom.SetTOWGS84(-121.8, 98.1, -10.7, 0, 0, 0.554, -0.2263) epsgto = SpatialReference() epsgto.ImportFromEPSG(epsg_to) if epsg_to != 4326: epsgto.SetTOWGS84(-121.8, 98.1, -10.7, 0, 0, 0.554, -0.2263) # ---------------------------- FromTo_psd = CoordinateTransformation(epsgfrom, epsgto) xlong, ylat, zcart = FromTo_psd.TransformPoint(cord_xlong, cord_ylat) # print(xlong,ylat,zcart) return (xlong, ylat, zcart)
def testInit(self): testFile1 = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'gsenm_250m_eucl_dist_streams.tif') workingCopy1 = tempfile.mkstemp(suffix='.tif')[1] shutil.copyfile(testFile1, workingCopy1) # Test valid SRS within the file. GeospatialImageFile(workingCopy1) # Test invalid SRS within the file. testFile2 = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'TSURF.nc') workingCopy2 = tempfile.mkstemp(suffix='.nc')[1] shutil.copyfile(testFile2, workingCopy2) with self.assertRaisesRegex(RuntimeError, 'Spatial reference for '): GeospatialImageFile(workingCopy2) # Test passing an SRS. srs = SpatialReference() srs.ImportFromEPSG(4326) imageFile = GeospatialImageFile(testFile2, spatialReference=srs) expectedSRS = SpatialReference() expectedSRS.ImportFromEPSG(4326) expectedSRS.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER) self.assertTrue(imageFile.srs().IsSame(expectedSRS)) # Test passing an invalid SRS. srs = SpatialReference() with self.assertRaisesRegex(RuntimeError, 'Spatial reference for '): imageFile = GeospatialImageFile(testFile2, spatialReference=srs) os.remove(workingCopy1) os.remove(workingCopy2)
def crs_from_epsg(epsg): """Create SpatialReference from EPSG code :param epsg: EPSG code representing of the spatial reference frame :type epsg: int :returns: SpatialReference object :rtype: SpatialReference """ proj = SpatialReference() proj.ImportFromEPSG(epsg) return proj
def getWKT_PRJ(epsg_code): # generate a .prj file based off epsg from input # as of 4.16/2019, spatialreference.org is down. Use GDAL API instead #wkt = urllib.urlopen("http://spatialreference.org/ref/epsg/{0}/prettywkt/".format(epsg_code)) #remove_spaces = wkt.read().replace(" ","") #output = remove_spaces.replace("\n", "") from osgeo.osr import SpatialReference srs = SpatialReference() srs.ImportFromEPSG(epsg_code) outWKT = srs.ExportToWkt() return str(outWKT)