Is it possible to use pyproj to transform WKT without creating geometry objects such shapely geometry, GEOS geometry or OGR geometry.
If not what is the fastest way to do it?
3 Answers 3
Sure. In that case, you need to transform each point separately. First parse WKT and extract point coordinates, then loop over coordinates and perform transformation like:
import pyproj
srcProj = pyproj.Proj(init='epsg:%i' % epsg_in, preserve_units=True)
dstProj = pyproj.Proj(init='epsg:%i' % epsg_out, preserve_units=True)
x_out,y_out = pyproj.transform(srcProj, dstProj, x_in, y_in)
-
alright, but parsing and reconstructing WKT is not that easy for multipolygon for instanceBelow the Radar– Below the Radar2014年08月06日 17:25:41 +00:00Commented Aug 6, 2014 at 17:25
-
you might want to take a look at shapely toblerity.org/shapely/manual.html#well-known-formatsMatej– Matej2014年08月06日 18:07:40 +00:00Commented Aug 6, 2014 at 18:07
Also check out Lars Butler's https://github.com/larsbutler/geomet, a pure Python WKT/WKB <-> GeoJSON converter.
-
Yes, I am using it to convert fiona f['geometry'] to WKT. Thank you @sgilliesBelow the Radar– Below the Radar2014年08月06日 14:26:59 +00:00Commented Aug 6, 2014 at 14:26
If you cannot or don't want to use Shapely, you could use those functions:
import re
from pyproj import CRS
from pyproj import Transformer
wgs84_wkt = "POLYGON((9.175287 48.780916, 9.185501 48.777522, 9.181467 48.773704, 9.174429 48.768472, 9.168807 48.773902, 9.175287 48.780916))"
COORDINATES_REGEX = re.compile(r"(\-?\d+\.\d*) (\-?\d+\.\d*)")
TO_LOCAL_CRS = Transformer.from_crs(CRS.from_epsg(4326),
CRS.from_epsg(32632),
always_xy=True)
def convert_coordinates(match):
longitude, latitude = match.groups()
x, y = TO_LOCAL_CRS.transform(longitude, latitude)
return f"{x} {y}"
def convert_wkt_to_local(wkt):
return COORDINATES_REGEX.sub(convert_coordinates, wkt)
print(convert_wkt_to_local(wgs84_wkt))
# POLYGON((512877.0688394928 5403116.534101295, 513628.3360295398 5402741.031035185, 513332.97838651366 5402315.905104928, 512817.2051751098 5401733.104146439, 512402.75806575816 5402335.776478222, 512877.0688394928 5403116.534101295))
It simply looks for longitude and latitude via regex, and converts the coordinates. It should work fine with holes or multipolygons too.