Python osr.CoordinateTransformation() Examples

The following are 9 code examples of osr.CoordinateTransformation(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module osr , or try the search function .
Example #1
Source File: gdal_interfaces.py    From open-elevation with GNU General Public License v2.0 6 votes vote down vote up
def loadMetadata(self):
        # open the raster and its spatial reference
        self.src = gdal.Open(self.tif_path)

        if self.src is None:
            raise Exception('Could not load GDAL file "%s"' % self.tif_path)
        spatial_reference_raster = osr.SpatialReference(self.src.GetProjection())

        # get the WGS84 spatial reference
        spatial_reference = osr.SpatialReference()
        spatial_reference.ImportFromEPSG(4326)  # WGS84

        # coordinate transformation
        self.coordinate_transform = osr.CoordinateTransformation(spatial_reference, spatial_reference_raster)
        gt = self.geo_transform = self.src.GetGeoTransform()
        dev = (gt[1] * gt[5] - gt[2] * gt[4])
        self.geo_transform_inv = (gt[0], gt[5] / dev, -gt[2] / dev,
                                  gt[3], -gt[4] / dev, gt[1] / dev) 
Example #2
Source File: my_types.py    From pydem with Apache License 2.0 6 votes vote down vote up
def to_wkt(self, target_wkt):
        # If we're going from WGS84 -> Spherical Mercator, use PyProj, because
        #  there seems to be a bug in OGR that gives us an offset. (GDAL
        #  does fine, though.
        if target_wkt == self.wkt:
            return self
        import osr
        dstSpatialRef = osr.SpatialReference()
        dstSpatialRef.ImportFromEPSG(d_name_to_epsg[target_wkt])
        # dstSpatialRef.ImportFromWkt(d_name_to_wkt[target_wkt])
        srcSpatialRef = osr.SpatialReference()
        srcSpatialRef.ImportFromEPSG(d_name_to_epsg[self.wkt])
        # srcSpatialRef.ImportFromWkt(self.wkt_)
        coordTransform = osr.CoordinateTransformation(srcSpatialRef, dstSpatialRef)
        a, b, c = coordTransform.TransformPoint(self.lon, self.lat)
        return Point(b, a, wkt=target_wkt) 
Example #3
Source File: terrain_correction.py    From pyeo with GNU General Public License v3.0 5 votes vote down vote up
def get_pixel_latlon(raster, x, y):
    """For a given pixel in raster, gets the lat-lon value in EPSG 4326."""
    # TODO: Move to coordinate_manipulation
    native_projection = osr.SpatialReference()
    native_projection.ImportFromWkt(raster.GetProjection())
    latlon_projection = osr.SpatialReference()
    latlon_projection.ImportFromEPSG(4326)
    transformer = osr.CoordinateTransformation(native_projection, latlon_projection)

    geotransform = raster.GetGeoTransform()
    x_geo, y_geo = cm.pixel_to_point_coordinates([y,x], geotransform)  # Why did I do this reverse?
    lon, lat, _ = transformer.TransformPoint(x_geo, y_geo)
    return lat, lon 
Example #4
Source File: terrain_correction.py    From pyeo with GNU General Public License v3.0 5 votes vote down vote up
def _generate_latlon_transformer(raster):
    native_projection = osr.SpatialReference()
    native_projection.ImportFromWkt(raster.GetProjection())
    latlon_projection = osr.SpatialReference()
    latlon_projection.ImportFromEPSG(4326)
    geotransform = raster.GetGeoTransform()
    return osr.CoordinateTransformation(native_projection, latlon_projection), geotransform 
Example #5
Source File: modis_tg_halli.py    From hydrology with GNU General Public License v3.0 5 votes vote down vote up
def reproject_dataset(dataset, output_file_name, wkt_from="+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs", epsg_to=32643, pixel_spacing=1000, file_format='GTiff'):
    '''
    :param dataset: Modis subset name use gdal.GetSubdatasets()
    :param output_file_name: file location along with proper extension
    :param wkt_from: Modis wkt (default)
    :param epsg_to: integer default(32643)
    :param pixel_spacing: in metres
    :param file_format: default GTiff
    :return:
    '''
    wgs84 = osr.SpatialReference()
    wgs84.ImportFromEPSG(epsg_to)
    modis = osr.SpatialReference()
    modis.ImportFromProj4(wkt_from)
    tx = osr.CoordinateTransformation(modis, wgs84)
    g = gdal.Open(dataset)
    geo_t = g.GetGeoTransform()
    print geo_t
    x_size = g.RasterXSize
    y_size = g.RasterYSize
    (ulx, uly, ulz) = tx.TransformPoint(geo_t[0], geo_t[3])
    (lrx, lry, lrz) = tx.TransformPoint(geo_t[0] + (geo_t[1]*x_size), geo_t[3]+ (geo_t[5]*y_size))
    mem_drv = gdal.GetDriverByName(file_format)
    dest = mem_drv.Create(output_file_name, int((lrx-ulx)/pixel_spacing), int((uly - lry)/pixel_spacing), 1, gdal.GDT_Float32)
    new_geo = ([ulx, pixel_spacing, geo_t[2], uly, geo_t[4], -pixel_spacing])
    dest.SetGeoTransform(new_geo)
    dest.SetProjection(wgs84.ExportToWkt())
    gdal.ReprojectImage(g, dest, modis.ExportToWkt(), wgs84.ExportToWkt(), gdal.GRA_Bilinear)
    print "reprojected" 
Example #6
Source File: vector.py    From OpenSarToolkit with MIT License 5 votes vote down vote up
def reproject_geometry(geom, inproj4, out_epsg):
    '''Reproject a wkt geometry based on EPSG code

    Args:
        geom (ogr-geom): an ogr geom objecct
        inproj4 (str): a proj4 string
        out_epsg (str): the EPSG code to which the geometry should transformed

    Returns
        geom (ogr-geometry object): the transformed geometry

    '''

    geom = ogr.CreateGeometryFromWkt(geom)
    # input SpatialReference
    spatial_ref_in = osr.SpatialReference()
    spatial_ref_in.ImportFromProj4(inproj4)

    # output SpatialReference
    spatial_ref_out = osr.SpatialReference()
    spatial_ref_out.ImportFromEPSG(int(out_epsg))

    # create the CoordinateTransformation
    coord_transform = osr.CoordinateTransformation(spatial_ref_in,
                                                   spatial_ref_out)
    try:
        geom.Transform(coord_transform)
    except:
        print(' ERROR: Not able to transform the geometry')
        sys.exit()

    return geom 
Example #7
Source File: utils.py    From cube-in-a-box with MIT License 5 votes vote down vote up
def transform_to_wgs(getLong, getLat, EPSGa):
    source = osr.SpatialReference()
    source.ImportFromEPSG(EPSGa)

    target = osr.SpatialReference()
    target.ImportFromEPSG(4326)

    transform = osr.CoordinateTransformation(source, target)

    point = ogr.CreateGeometryFromWkt("POINT (" + str(getLong[0]) + " " + str(getLat[0]) + ")")
    point.Transform(transform)
    return [point.GetX(), point.GetY()] 
Example #8
Source File: utils.py    From gips with GNU General Public License v2.0 5 votes vote down vote up
def transform_shape(shape, ssrs, tsrs):
    """ Transform shape from ssrs to tsrs (all wkt) and return as wkt """
    ogrgeom = CreateGeometryFromWkt(shape)
    trans = CoordinateTransformation(SpatialReference(ssrs), SpatialReference(tsrs))
    ogrgeom.Transform(trans)
    wkt = ogrgeom.ExportToWkt()
    ogrgeom = None
    return wkt 
Example #9
Source File: nlcd_origin.py    From Spectrum-Access-System with Apache License 2.0 4 votes vote down vote up
def __init__(self, tile_path):
    """Initializes the Tile Information.

    Inputs:
      tile_path: path the tile file.
    """
    self.tile_path = tile_path

    ds = gdal.Open(tile_path)
    self.width = ds.RasterXSize
    self.height = ds.RasterYSize

    # Gets the gdal geo transformation tuples
    gdal_version = osgeo.gdal.__version__
    self._txf = ds.GetGeoTransform()
    if gdal_version[0] == '1':
      self._inv_txf = gdal.InvGeoTransform(self._txf)[1]
    else:
      self._inv_txf = gdal.InvGeoTransform(self._txf)
    # Gets the transformation from lat/lon to coordinates
    wgs84_ref = osr.SpatialReference()
    wgs84_ref.ImportFromEPSG(4326)   # WGS84
    sref = osr.SpatialReference()
    sref.ImportFromWkt(ds.GetProjection())
    self._transform = osr.CoordinateTransformation(wgs84_ref, sref)
    inv_transform = osr.CoordinateTransformation(sref, wgs84_ref)
    # Find a loose lat/lon bounding box  for quick check without
    # having to do full coordinates transformation
    corners = []
    for x in [0, self.width]:
      for y in [0, self.height]:
        corners.append([self._txf[0] + self._txf[1] * x + self._txf[2] * y,
                        self._txf[3] + self._txf[4] * x + self._txf[5] * y])
    self.max_lat = -100
    self.min_lat = 100
    self.max_lon = -500
    self.min_lon = 500
    for c in corners:
      p = inv_transform.TransformPoint(c[0], c[1])
      if p[0] > self.max_lon:
        self.max_lon = p[0]
      if p[0] < self.min_lon:
        self.min_lon = p[0]
      if p[1] > self.max_lat:
        self.max_lat = p[1]
      if p[1] < self.min_lat:
        self.min_lat = p[1]

    # Close file
    ds = None