Exemplo n.º 1
0
def osr_ct_6():

    if gdaltest.have_proj4 == 0:
        return 'skip'

    ct = osr.CreateCoordinateTransformation(None, None)
    if ct is not None:
        return 'fail'

    utm_srs = osr.SpatialReference()
    utm_srs.SetUTM(11)
    utm_srs.SetWellKnownGeogCS('WGS84')

    ll_srs = osr.SpatialReference()
    ll_srs.SetWellKnownGeogCS('WGS84')

    ct = osr.CreateCoordinateTransformation(ll_srs, utm_srs)
    if ct is None:
        return 'fail'

    result = ct.TransformPoints(((-117.5, 32.0, 0.0), (-117.5, 32.0)))

    for i in range(2):
        if abs(result[i][0] - 452772.06) > 0.01 \
                or abs(result[i][1] - 3540544.89) > 0.01 \
                or abs(result[i][2] - 0.0) > 0.01:
            gdaltest.post_reason('Wrong LL to UTM result')
            return 'fail'

    return 'success'
Exemplo n.º 2
0
 def setParams(layer):
     srs = layer.GetSpatialRef()
     wkt7390 = 'PROJCS["Brazil / Albers Equal Area Conic (WGS84)",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["longitude_of_center",-50.0],PARAMETER["standard_parallel_1",10.0],PARAMETER["standard_parallel_2",-40.0],PARAMETER["latitude_of_center",-25.0],UNIT["Meter",1.0]]'
     sr7390 = osr.SpatialReference()
     sr7390.ImportFromWkt(wkt7390)
     AggregatorParams.srs = srs
     AggregatorParams.ctArea = osr.CreateCoordinateTransformation(
         srs, sr7390)
     AggregatorParams.ctOrigin = osr.CreateCoordinateTransformation(
         sr7390, srs)
Exemplo n.º 3
0
    def _get_transforms(self, sr_origin, rect, rect_from='origin'):
        """Retrieve the `to_work` and `to_origin` conversion functions.

        Parameters
        ----------
        sr_origin: osr.SpatialReference
        rect: Footprint or extent or None
        rect_from: one of ('origin', 'work')
        """
        assert rect_from in ['origin', 'work']

        if not self._sr_work:
            return None, None
        if self._sr_origin:
            sr_origin = self._sr_origin
        elif not sr_origin:
            if self._sr_implicit:
                sr_origin = self._sr_implicit
            else:
                raise ValueError("Missing origin's spatial reference")

        to_work = osr.CreateCoordinateTransformation(
            sr_origin, self._sr_work).TransformPoints
        to_origin = osr.CreateCoordinateTransformation(
            self._sr_work, sr_origin).TransformPoints

        to_work = self._make_transfo(to_work)
        to_origin = self._make_transfo(to_origin)

        if self._analyse_transformations:
            if rect_from == 'origin':
                an = srs.Analysis(to_work, to_origin, rect)
            else:
                an = srs.Analysis(to_origin, to_work, rect)
            if rect is None:
                pass
            elif isinstance(rect, Footprint):
                if not an.ratio_valid:
                    raise ValueError(
                        'Bad coord transformation for raster proxy: {}'.format(
                            an.messages))
            else:
                minx, maxx, miny, maxy = rect
                if minx != maxx and miny != maxy:
                    if not an.inverse_valid:
                        raise ValueError(
                            'Bad coord transformation for vector proxy: {}'.
                            format(an.messages))

        return to_work, to_origin
Exemplo n.º 4
0
 def pcs_2000_to_sz_local(self, points):
     helmert_para = helmert_para_dict(4547, 2435, "EAST")
     opt = osr.CoordinateTransformationOptions()
     opt.SetOperation(helmert_para)
     tr = osr.CreateCoordinateTransformation(None, None, opt)
     points = osr.CoordinateTransformation.TransformPoints(tr, points)
     return points
Exemplo n.º 5
0
def get_map_size():
	if param_reference in maps:
		refmap = maps[param_reference]
	else:
		print("Map", param_reference, "does not exist.")
		return
	if param_crop:
		if param_reproject:
			north, east, south, west = param_region
			minp = merc_transform.TransformPoint(west, south)
			maxp = merc_transform.TransformPoint(east, north)
			pxsize = param_hscale / np.cos(np.radians((north+south)/2))
			npx = (maxp[0]-minp[0]) // pxsize
			npy = (maxp[1]-minp[1]) // pxsize
			return int(npx), int(npy), 0, 0, pxsize
		else:
			gt = refmap.GetGeoTransform()
			proj = osr.SpatialReference()
			proj.ImportFromWkt(refmap.GetProjection())
			transform = osr.CreateCoordinateTransformation(wgs, proj)
			north, east, south, west = param_region
			xNW, yNW = gm.inverse(gt, transform.TransformPoint(west, north))
			xSE, ySE = gm.inverse(gt, transform.TransformPoint(east, south))
			xmin = np.floor(min(xNW, xSE)+.5)
			xmax = np.floor(max(xNW, xSE)+.5)
			ymin = np.floor(min(yNW, ySE)+.5)
			ymax = np.floor(max(yNW, ySE)+.5)
			return int(xmax-xmin+1), int(ymax-ymin+1), int(xmin), int(ymin), 0
	else:
		return refmap.RasterXSize, refmap.RasterYSize, 0, 0, 0
Exemplo n.º 6
0
def read_map(mapname, interp=gdal.GRA_NearestNeighbour):
	npx, npy, xmin, ymin, pxsize = get_map_size()
	if mapname in maps:
		map1 = maps[mapname]
	else:
		print("Map", mapname, "does not exist.")
		return

	print("Reading", mapname)
	if param_reproject:
		proj = mercator
		transform = merc_transform
		north, east, south, west = param_region
		origin = merc_transform.TransformPoint(west, north)
		geotransform = (origin[0], pxsize, 0., origin[1], 0., -pxsize)
	elif mapname == param_reference:
		return map1.ReadAsArray(xmin, ymin, npx, npy)
	else:
		refmap = maps[param_reference]
		proj = osr.SpatialReference()
		proj.ImportFromWkt(refmap.GetProjection())
		transform = osr.CreateCoordinateTransformation(wgs, proj)
		ref_gt = refmap.GetGeoTransform()
		origin = gm.transform(ref_gt, (xmin, ymin))
		geotransform = (origin[0], ref_gt[1], ref_gt[2], origin[1], ref_gt[4], ref_gt[5])
			
	map2 = drv.Create("", npx, npy, 1, map1.GetRasterBand(1).DataType)
	map2.SetGeoTransform(geotransform)
	print("Reprojecting", mapname)
	gdal.ReprojectImage(map1, map2, map1.GetProjection(), proj.ExportToWkt(), interp)
	return map2.ReadAsArray()
Exemplo n.º 7
0
        def run(self):
            try:
                conn = psycopg2.connect("dbname=" + str(self.database) + " user='******' host='" + str(self.host) + "' password='******'")
            except:
                print "I am unable to connect to the database"


            source_osr = osr.SpatialReference()
            source_osr.ImportFromEPSG(4326)
            target_osr = osr.SpatialReference()
            target_osr.ImportFromEPSG(32755)
            transformation = osr.CreateCoordinateTransformation(source_osr, target_osr)

            cur = conn.cursor()

            filter_query = ""
            if self.node_station.get_attribute_filter_sql_string(""):
                filter_query = "WHERE " + self.node_station.get_attribute_filter_sql_string("")

            cur.execute("SELECT * from station " + filter_query)
            rows = cur.fetchall()
            for r in rows:
                station = self.node_station.create_feature()

                station.SetField("dance_station_id", r[0])
                print r
                pt = ogr.Geometry(ogr.wkbPoint)
                pt.SetPoint_2D(0, r[4], r[5])
                pt.Transform(transformation)
                station.SetGeometry(pt)

            self.node_station.finalise()
Exemplo n.º 8
0
def CoordinateTransform(vertexs, srs, des):
    transformer = osr.CreateCoordinateTransformation(srs, des)
    result = np.empty((0, 2), float)
    for i in range(len(vertexs)):
        coords = transformer.TransformPoint(vertexs[i][0], vertexs[i][1])
        result = np.append(result, [[coords[0], coords[1]]], axis = 0)
    return result
Exemplo n.º 9
0
    def __init__(self, from_epsg: int, to_epsg: int):
        self._s_srs = osr.SpatialReference()
        self._s_srs.ImportFromEPSG(from_epsg)
        self._t_srs = osr.SpatialReference()
        self._t_srs.ImportFromEPSG(to_epsg)

        self._transform = osr.CreateCoordinateTransformation(
            self._s_srs, self._t_srs)
Exemplo n.º 10
0
 def proj_transform(self, srcSRS, dstSRS, points):
     sourceSRS = osr.SpatialReference()
     sourceSRS.ImportFromEPSG(srcSRS)
     destinationSRS = osr.SpatialReference()
     destinationSRS.ImportFromEPSG(dstSRS)
     tr = osr.CreateCoordinateTransformation(sourceSRS, destinationSRS)
     points = osr.CoordinateTransformation.TransformPoints(tr, points)
     return points
Exemplo n.º 11
0
    def get_transforms(self, sr_virtual, rect, rect_from='virtual'):
        """Retrieve the `to_work` and `to_virtual` conversion functions.

        Parameters
        ----------
        sr_virtual: osr.SpatialReference
        rect: Footprint or extent or None
        rect_from: one of ('virtual', 'work')
        """
        assert rect_from in ['virtual', 'work']

        if self.sr_work is None:
            return None, None

        assert sr_virtual is not None

        to_work = osr.CreateCoordinateTransformation(sr_virtual, self.sr_work).TransformPoints
        to_virtual = osr.CreateCoordinateTransformation(self.sr_work, sr_virtual).TransformPoints

        to_work = self._make_transfo(to_work)
        to_virtual = self._make_transfo(to_virtual)

        if self.analyse_transformations:
            if rect_from == 'virtual':
                an = srs.Analysis(to_work, to_virtual, rect)
            else:
                an = srs.Analysis(to_virtual, to_work, rect)
            if rect is None:
                pass
            elif isinstance(rect, Footprint):
                if not an.ratio_valid:
                    raise ValueError('Bad coord transformation for raster proxy: {}'.format(
                        an.messages
                    ))
            else:
                minx, maxx, miny, maxy = rect
                if minx != maxx and miny != maxy:
                    if not an.inverse_valid:
                        raise ValueError(
                            'Bad coord transformation for vector proxy: {}'.format(an.messages)
                        )

        return to_work, to_virtual
Exemplo n.º 12
0
 def __enter__(self):
     input_srs = osr.SpatialReference()
     input_srs.ImportFromEPSG(self.input_srid)
     data_srs = osr.SpatialReference()
     data_srs.ImportFromEPSG(self.datasource_srid)
     self.input_transform = osr.CreateCoordinateTransformation(
         input_srs, data_srs)
     self.dem = gdal.Open(self.datasource)
     self.data = self.dem.GetRasterBand(self.band)
     self.nodata = self.data.GetNoDataValue()
     return self
Exemplo n.º 13
0
def test_osr_ct_6():

    ct = osr.CreateCoordinateTransformation(None, None)
    assert ct is None

    utm_srs = osr.SpatialReference()
    utm_srs.SetUTM(11)
    utm_srs.SetWellKnownGeogCS('WGS84')

    ll_srs = osr.SpatialReference()
    ll_srs.SetWellKnownGeogCS('WGS84')
    ll_srs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)

    ct = osr.CreateCoordinateTransformation(ll_srs, utm_srs)
    assert ct is not None

    result = ct.TransformPoints(((-117.5, 32.0, 0.0), (-117.5, 32.0)))

    for i in range(2):
        assert result[i][0] == pytest.approx(452772.06, abs=0.01) and result[i][1] == pytest.approx(3540544.89, abs=0.01) and result[i][2] == pytest.approx(0.0, abs=0.01), \
            'Wrong LL to UTM result'
    def run(self):
        try:
            conn = psycopg2.connect("dbname=" + str(self.database) +
                                    " user='******' host='" + str(self.host) +
                                    "' password='******'")
        except:
            print("I am unable to connect to the database")

        source_osr = osr.SpatialReference()
        source_osr.ImportFromEPSG(4326)
        target_osr = osr.SpatialReference()
        target_osr.ImportFromEPSG(
            self.getSimulationConfig().getCoorindateSystem())
        transformation = osr.CreateCoordinateTransformation(
            source_osr, target_osr)

        cur = conn.cursor()

        filter_query = ""
        if self.node_station.get_attribute_filter_sql_string(""):
            filter_query = "WHERE " + self.node_station.get_attribute_filter_sql_string(
                "")

        if filter_query == "" and self.filter != "":
            filter_query = "WHERE " + self.filter
        elif self.filter != "":
            filter_query = filter_query + " AND " + self.filter

        log(filter_query, Standard)

        cur.execute("SELECT * from " + self.station_table + " " + filter_query)
        rows = cur.fetchall()
        for r in rows:
            station = self.node_station.create_feature()

            station.SetField("dance_station_id", r[0])
            station.SetField("name", r[1])

            station.SetField("description", r[2])
            station.SetField("short_description", r[3])

            station.SetField("start_date", str(r[8]))
            station.SetField("end_date", str(r[9]))
            print(r)
            pt = ogr.Geometry(ogr.wkbPoint)
            pt.SetPoint_2D(0, r[4], r[5])
            pt.Transform(transformation)
            station.SetGeometry(pt)

        self.node_station.finalise()
Exemplo n.º 15
0
def test_osr_ct_6():

    if gdaltest.have_proj4 == 0:
        pytest.skip()

    ct = osr.CreateCoordinateTransformation(None, None)
    assert ct is None

    utm_srs = osr.SpatialReference()
    utm_srs.SetUTM(11)
    utm_srs.SetWellKnownGeogCS('WGS84')

    ll_srs = osr.SpatialReference()
    ll_srs.SetWellKnownGeogCS('WGS84')

    ct = osr.CreateCoordinateTransformation(ll_srs, utm_srs)
    assert ct is not None

    result = ct.TransformPoints(((-117.5, 32.0, 0.0), (-117.5, 32.0)))

    for i in range(2):
        assert abs(result[i][0] - 452772.06) <= 0.01 and abs(result[i][1] - 3540544.89) <= 0.01 and abs(result[i][2] - 0.0) <= 0.01, \
            'Wrong LL to UTM result'
Exemplo n.º 16
0
def LATLONG_TO_XY(path_to_tiff, lat, long):
    data = gdal.Open(path_to_tiff)
    target = osr.SpatialReference(wkt=data.GetProjection())
    source = osr.SpatialReference()
    source.ImportFromEPSG(4326)
    transform = osr.CreateCoordinateTransformation(source, target)

    point = ogr.Geometry(ogr.wkbPoint)
    point.AddPoint(lat, long)
    point.Transform(transform)

    x, y = world_to_pixel(path_to_tiff, data.GetGeoTransform(), point.GetX(),
                          point.GetY())
    list1 = [x, y]
    return list1
Exemplo n.º 17
0
def get_map_bounds(mapname):
	if mapname in maps:
		thismap = maps[mapname]
	else:
		print("Map", mapname, "does not exist.")
		return
	xsize, ysize = thismap.RasterXSize, thismap.RasterYSize
	gt = thismap.GetGeoTransform()
	proj = osr.SpatialReference()
	proj.ImportFromWkt(thismap.GetProjection())
	transform = osr.CreateCoordinateTransformation(proj, wgs)
	minp = gm.transform(gt, (0, 0))
	maxp = gm.transform(gt, (xsize, ysize))
	xmin, ymin, _ = transform.TransformPoint(minp[0], minp[1])
	xmax, ymax, _ = transform.TransformPoint(maxp[0], maxp[1])
	north = max(ymin, ymax) # Maps might be reversed, so we're not sure which one is actually the maximum
	east = max(xmin, xmax)
	south = min(ymin, ymax)
	west = min(xmin, xmax)
	return (north, east, south, west)
Exemplo n.º 18
0
def test_proj_transformation_grid():
    import kart  # noqa
    from osgeo import osr

    # note kart.__init__ sets PROJ_NETWORK=ON and PROJ_LIB to the proj data files
    # during tests $HOME is changed to a temporary dir, so downloaded grids in the
    # user proj data dir will be empty/missing
    # TODO: except for windows where somehow it's buggy and we get a network error
    print("PROJ/GDAL-related environment variables:")
    for k, v in os.environ.items():
        if re.match(r"^(GDAL|PROJ|CPL)_", k):
            print(f"${k}={v}")

    print("osr.GetPROJSearchPaths():", osr.GetPROJSearchPaths())
    print("osr.GetPROJAuxDbPaths():", osr.GetPROJAuxDbPaths())
    # print("osr.GetPROJEnableNetwork():", osr.GetPROJEnableNetwork())  # not in the Python bindings yet

    # Do a test conversion to check the transformation grids are available
    nzgd49 = osr.SpatialReference()
    nzgd49.ImportFromEPSG(4272)  # NZGD1949
    nzgd2k = osr.SpatialReference()
    nzgd2k.ImportFromEPSG(4167)  # NZGD2000
    ct = osr.CreateCoordinateTransformation(nzgd49, nzgd2k)
    # Test point from: https://www.linz.govt.nz/data/geodetic-system/coordinate-conversion/geodetic-datum-conversions/datum-transformation-examples
    pt = ct.TransformPoint(-36.5, 175.0)

    # Equivalent commands:
    # $ echo 175.0 -36.5 | PROJ_DEBUG=2 CPL_DEBUG=ON gdaltransform -s_srs EPSG:4272 -t_srs EPSG:4167
    # $ echo -36.5 175.0 0 | PROJ_DEBUG=2 cs2cs -v -f "%.8f" EPSG:4272 EPSG:4167

    if not is_windows:
        # This is the (desired) accurate result expected when the transformation grid is available:
        assert pt == pytest.approx((-36.49819023, 175.00019297, 0.0), abs=1e-8)
    else:
        # This is the less accurate result which uses the 7-parameter transform,
        # which indicates that the transformation grid is not available
        #
        # Currently the Windows proj libraries are built without network
        # support, so we can't auto-fetch grids
        assert pt == pytest.approx((-36.49819267, 175.00018527, 0.0), abs=1e-8)
Exemplo n.º 19
0
def create_coordinate_transformer(
        base_ref,
        target_ref,
        osr_axis_mapping_strategy=DEFAULT_OSR_AXIS_MAPPING_STRATEGY):
    """Create a spatial reference coordinate transformation function.

    Args:
        base_ref (osr spatial reference): A defined spatial reference to
            transform FROM
        target_ref (osr spatial reference): A defined spatial reference
            to transform TO
        osr_axis_mapping_strategy (int): OSR axis mapping strategy for
            ``SpatialReference`` objects. Defaults to
            ``utils.DEFAULT_OSR_AXIS_MAPPING_STRATEGY``. This parameter should
            not be changed unless you know what you are doing.

    Returns:
        An OSR Coordinate Transformation object

    """
    # Make a copy of the base and target spatial references to avoid side
    # effects from mutation of setting the axis mapping strategy
    base_ref_wkt = base_ref.ExportToWkt()
    target_ref_wkt = target_ref.ExportToWkt()

    base_ref_copy = osr.SpatialReference()
    target_ref_copy = osr.SpatialReference()

    base_ref_copy.ImportFromWkt(base_ref_wkt)
    target_ref_copy.ImportFromWkt(target_ref_wkt)

    base_ref_copy.SetAxisMappingStrategy(osr_axis_mapping_strategy)
    target_ref_copy.SetAxisMappingStrategy(osr_axis_mapping_strategy)

    transformer = osr.CreateCoordinateTransformation(base_ref_copy,
                                                     target_ref_copy)
    return transformer
Exemplo n.º 20
0
    def _get_center_coords(self, wkt, geotransform, data_shape):

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

        spatial = osr.SpatialReference()
        spatial.ImportFromWkt(wkt)

        affine_transform = AffineGlobalCoords(geotransform)

        if len(data_shape) == 3:
            y_size = data_shape[1]
            x_size = data_shape[2]

        else:
            y_size = data_shape[0]
            x_size = data_shape[1]

        transform = osr.CreateCoordinateTransformation(spatial, wgs84)
        proj_y, proj_x = affine_transform.getProjectedYX(
            y_size / 2, x_size / 2)
        center_lon, center_lat = transform.TransformPoint(proj_x, proj_y)[:2]

        return center_lon, center_lat
Exemplo n.º 21
0
def convert_geometry(
        geometry: ogr.Geometry,
        new_spatialreference: osr.SpatialReference) -> ogr.Geometry:
    """Converts the geometry to the new spatial reference if possible
    Arguments:
        geometry - The geometry to transform
        new_spatialreference - The spatial reference to change to
    Returns:
        The transformed geometry or the original geometry. If either the
        new Spatial Reference parameter is None, or the geometry doesn't
        have a spatial reference, then the original geometry is returned.
    """
    if not new_spatialreference or not geometry:
        return geometry

    return_geometry = geometry
    try:
        geom_sr = geometry.GetSpatialReference()
        if int(osgeo.__version__[0]) >= 3:
            # GDAL 3 changes axis order: https://github.com/OSGeo/gdal/issues/1546
            # pylint: disable=no-member
            geom_sr.SetAxisMappingStrategy(
                osgeo.osr.OAMS_TRADITIONAL_GIS_ORDER)
        if geom_sr and not new_spatialreference.IsSame(geom_sr):
            transform = osr.CreateCoordinateTransformation(
                geom_sr, new_spatialreference)
            new_geom = geometry.Clone()
            if new_geom:
                new_geom.Transform(transform)
                return_geometry = new_geom
    except Exception as ex:
        logging.warning("Exception caught while transforming geometries: %s",
                        str(ex))
        logging.warning("    Returning original geometry")

    return return_geometry
def extract_grid_ppt(sub_netcdf_list, in_cat_shp, sub_out_cat_data_df, ppt_que):

    '''
    Extract precipitation from a given list of netCDf files
        The catchments shapefile can have one more catchment polygons.
        Change names of variables and values inside the function,
        (not everything is specified through the arguments).
    '''
    cat_vec = ogr.Open(in_cat_shp)
    lyr = cat_vec.GetLayer(0)

    spt_ref = lyr.GetSpatialRef()
    trgt = osr.SpatialReference()
    trgt.ImportFromEPSG(4326)
    tfm = osr.CreateCoordinateTransformation(spt_ref, trgt)
    back_tfm = osr.CreateCoordinateTransformation(trgt, spt_ref)

    #raise Exception

    feat_dict = {}
    feat_area_dict = {}
    cat_area_ratios_dict = {}
    cat_envel_dict = {}

    feat = lyr.GetNextFeature()

    while feat:
        geom = feat.GetGeometryRef()
        f_val = feat.GetFieldAsString('DN')
        if f_val is None:
            raise RuntimeError

        feat_area_dict[f_val] = geom.Area() # do before transform

        geom.Transform(tfm)
        feat_dict[f_val] = feat

        cat_envel_dict[f_val] = geom.GetEnvelope() # do after transform
        feat = lyr.GetNextFeature()

    for netcdf in sub_netcdf_list:
        #print 'Going through: %s' % netcdf
        in_nc = nc.Dataset(netcdf)
        lat_arr = in_nc.variables['latitude'][:]
        lon_arr = in_nc.variables['longitude'][:]

        apply_cell_correc = True

        # convert the netCDF time to regular time
        time_var = in_nc.variables['time']
        time_arr =  nc.num2date(in_nc.variables['time'][:],
                                time_var.units,
                                calendar=time_var.calendar)

        ppt_var = in_nc.variables['precip']

        #print 'Counting time from (in the netCDF file):',time_var.units
        #print 'Start date in the netCDF: ', time_arr[0]
        #print 'End date in the netCDF: ', time_arr[-1]
        #print 'Total time steps in the netCDF: ', time_arr.shape[0]

        cell_size = round(lon_arr[1] - lon_arr[0], 3)
        x_l_c = lon_arr[0]
        x_u_c = lon_arr[-1]
        y_l_c = lat_arr[0]
        y_u_c = lat_arr[-1]
        #raise Exception

        if apply_cell_correc:  # because CHIRPS has values at the center of the cell
                                   # so I shift it back
            x_l_c -= (cell_size/2.)
            x_u_c -= (cell_size/2.)
            y_l_c -= (cell_size/2.)
            y_u_c -= (cell_size/2.)

        x_coords = np.arange(x_l_c, x_u_c * 1.00000001, cell_size)# - (cell_size / 2)
        y_coords = np.arange(y_l_c, y_u_c * 1.00000001, cell_size)# - (cell_size / 2)

        cat_x_idxs_dict = {}
        cat_y_idxs_dict = {}

        for cat_no in list(feat_dict.keys()):
            #print 'Cat no:', cat_no
            geom = feat_dict[cat_no].GetGeometryRef()

            extents = cat_envel_dict[cat_no]
            cat_area = feat_area_dict[cat_no]

            inter_areas = []
            x_low, x_hi, y_low, y_hi = extents

            # adjustment to get all cells intersecting the polygon
            x_low, x_hi, y_low, y_hi = x_low - cell_size, x_hi + cell_size, y_low - cell_size, y_hi + cell_size
            x_cors_idxs = np.where(np.logical_and(x_coords >= x_low, x_coords <= x_hi))[0]
            y_cors_idxs = np.where(np.logical_and(y_coords >= y_low, y_coords <= y_hi))[0]

            x_cors = x_coords[x_cors_idxs]
            y_cors = y_coords[y_cors_idxs]

            cat_x_idxs = []
            cat_y_idxs = []

            for x_idx in range(x_cors.shape[0] - 1):
                for y_idx in range(y_cors.shape[0] - 1):
                    ring = ogr.Geometry(ogr.wkbLinearRing)

                    ring.AddPoint(x_cors[x_idx], y_cors[y_idx])
                    ring.AddPoint(x_cors[x_idx + 1], y_cors[y_idx])
                    ring.AddPoint(x_cors[x_idx + 1], y_cors[y_idx + 1])
                    ring.AddPoint(x_cors[x_idx], y_cors[y_idx + 1])
                    ring.AddPoint(x_cors[x_idx], y_cors[y_idx])

                    poly = ogr.Geometry(ogr.wkbPolygon)
                    poly.AddGeometry(ring)

                    inter_poly = poly.Intersection(geom)
                    # to get the area, I convert it to coordinate sys of the shapefile
                        # that is hopefully in linear units
                    inter_poly.Transform(back_tfm)
                    inter_area = inter_poly.Area()

                    inter_areas.append(inter_area)

                    cat_x_idxs.append((x_cors[x_idx] - x_l_c) / cell_size)
                    cat_y_idxs.append((y_cors[y_idx] - y_l_c) / cell_size)

            cat_area_ratios_dict[cat_no] = np.divide(inter_areas, cat_area)

            cat_x_idxs_dict[cat_no] = np.int64(np.round(cat_x_idxs, 6))
            cat_y_idxs_dict[cat_no] = np.int64(np.round(cat_y_idxs, 6))
            #print 'Normalized area sum:', np.sum(cat_area_ratios_dict[cat_no])

        for idx, date in enumerate(time_arr):
            if date in sub_out_cat_data_df.index:
                all_ppt_vals = ppt_var[idx]
                for cat_no in list(feat_dict.keys()):
                    ppt_vals = all_ppt_vals[cat_y_idxs_dict[cat_no], cat_x_idxs_dict[cat_no]]
                    fin_ppt_vals = np.multiply(ppt_vals, cat_area_ratios_dict[cat_no])
                    sub_out_cat_data_df.loc[date][cat_no] = round(np.sum(fin_ppt_vals), 2)

        #print '\n\n'
        in_nc.close()

    ppt_que.put(sub_out_cat_data_df)
    cat_vec.Destroy()
    return
Exemplo n.º 23
0
  def features(self, request=None, clipGeom=None):
    settings = self.writer.settings
    mapTo3d = settings.mapTo3d()
    baseExtent = settings.baseExtent
    baseExtentGeom = baseExtent.geometry()
    rotation = baseExtent.rotation()
    prop = self.prop

    useZ = prop.useZ()
    if useZ:
      srs_from = osr.SpatialReference()
      srs_from.ImportFromProj4(str(self.layer.crs().toProj4()))
      srs_to = osr.SpatialReference()
      srs_to.ImportFromProj4(str(self.writer.settings.crs.toProj4()))

      ogr_transform = osr.CreateCoordinateTransformation(srs_from, srs_to)
      clipGeomWkb = bytes(clipGeom.exportToWkb()) if clipGeom else None
      ogr_clipGeom = ogr.CreateGeometryFromWkb(clipGeomWkb) if clipGeomWkb else None

    else:
      # z_func: function to get elevation at given point (x, y) on surface
      if prop.isHeightRelativeToDEM():
        if self.geomType == QgsWkbTypes.PolygonGeometry and prop.type_index == 1:  # Overlay
          z_func = lambda x, y: 0
        else:
          # get elevation from DEM
          z_func = lambda x, y: self.writer.demProvider.readValue(x, y)
      else:
        z_func = lambda x, y: 0

    feats = []
    request = request or QgsFeatureRequest()
    for f in self.layer.getFeatures(request):
      geometry = f.geometry()
      if geometry is None:
        logMessage("null geometry skipped")
        continue

      # coordinate transformation - layer crs to project crs
      geom = QgsGeometry(geometry)
      if geom.transform(self.transform) != 0:
        logMessage("Failed to transform geometry")
        continue

      # check if geometry intersects with the base extent (rotated rect)
      if rotation and not baseExtentGeom.intersects(geom):
        continue

      # create feature
      feat = Feature(self.writer, self, f)

      # transform_func: function to transform the map coordinates to 3d coordinates
      relativeHeight = prop.relativeHeight(f)

      def transform_func(x, y, z):
        return mapTo3d.transform(x, y, z + relativeHeight)

      if useZ:
        ogr_geom = ogr.CreateGeometryFromWkb(bytes(geometry.exportToWkb()))

        # transform geometry from layer CRS to project CRS
        if ogr_geom.Transform(ogr_transform) != 0:
          logMessage("Failed to transform geometry")
          continue

        # clip geometry
        if ogr_clipGeom and self.geomType == QgsWkbTypes.LineGeometry:
          ogr_geom = ogr_geom.Intersection(ogr_clipGeom)
          if ogr_geom is None:
            continue

        # check if geometry is empty
        if ogr_geom.IsEmpty():
          logMessage("empty geometry skipped")
          continue

        feat.geom = self.geomClass.fromOgrGeometry25D(ogr_geom, transform_func)

      else:
        # clip geometry
        if clipGeom and self.geomType in [QgsWkbTypes.LineGeometry, QgsWkbTypes.PolygonGeometry]:
          geom = geom.intersection(clipGeom)
          if geom is None:
            continue

        # skip if geometry is empty or null
        if geom.isEmpty() or geom.isNull():
          logMessage("empty/null geometry skipped")
          continue

        if self.geomType == QgsWkbTypes.PolygonGeometry:
          feat.geom = self.geomClass.fromQgsGeometry(geom, z_func, transform_func, self.hasLabel())
          if prop.type_index == 1 and prop.isHeightRelativeToDEM():   # Overlay and relative to DEM
            feat.geom.splitPolygon(self.writer.triangleMesh())

        else:
          feat.geom = self.geomClass.fromQgsGeometry(geom, z_func, transform_func)

      if feat.geom is None:
        continue

      #yield feat
      feats.append(feat)

    return feats
def zonal_stats(vector_path, raster_path, nodata_value):

    # open raster layer
    rds = gdal.Open(raster_path, GA_ReadOnly)
    assert (rds)
    rb = rds.GetRasterBand(1)
    rgt = rds.GetGeoTransform()

    # set raster nodata value
    if nodata_value:
        nodata_value = float(nodata_value)
        rb.SetNoDataValue(nodata_value)

    # open vector layer
    vds = ogr.Open(vector_path, GA_ReadOnly)
    assert (vds)
    vlyr = vds.GetLayer(0)

    # compare EPSG values of vector and raster and change projection if necessary
    sourceSR = vlyr.GetSpatialRef()
    sourceSR.AutoIdentifyEPSG()
    EPSG_sourceSR = sourceSR.GetAuthorityCode(None)

    targetSR = osr.SpatialReference(wkt=rds.GetProjection())
    targetSR.AutoIdentifyEPSG()
    EPSG_targetSR = targetSR.GetAuthorityCode(None)

    if EPSG_sourceSR != EPSG_sourceSR:
        # reproject vector geometry to same projection as raster
        print 'unequal projections'
        sourceSR = vlyr.GetSpatialRef()
        targetSR = osr.SpatialReference()
        targetSR.ImportFromWkt(rds.GetProjectionRef())
        coordTrans = osr.CreateCoordinateTransformation(sourceSR, targetSR)
    """do the work"""
    global_src_extent = None
    mem_drv = ogr.GetDriverByName('Memory')
    driver = gdal.GetDriverByName('MEM')

    # Loop through vectors
    stats = []
    feat = vlyr.GetNextFeature()

    while feat is not None:
        # print statement after each hunderds features
        fid = int(feat.GetFID())
        prov = str(feat.GetField('NAME_1'))
        print("start with feature %s " % (fid))
        print("province: %s " % (prov))
        #if fid % 500 == 0:
        #    print("finished first %s features" % (fid))

        if not global_src_extent:
            #print 'bbox county'
            # use local source extent
            # fastest option when you have fast disks and well indexed raster (ie tiled Geotiff)
            # advantage: each feature uses the smallest raster chunk
            # disadvantage: lots of reads on the source raster
            src_offset = bbox_to_pixel_offsets(rgt,
                                               feat.geometry().GetEnvelope())
            src_array = rb.ReadAsArray(*src_offset)

            # calculate new geotransform of the feature subset
            new_gt = ((rgt[0] + (src_offset[0] * rgt[1])), rgt[1], 0.0,
                      (rgt[3] + (src_offset[1] * rgt[5])), 0.0, rgt[5])

        # Create a temporary vector layer in memory
        mem_ds = mem_drv.CreateDataSource('out')
        mem_layer = mem_ds.CreateLayer('poly', None, ogr.wkbPolygon)
        mem_layer.CreateFeature(feat.Clone())

        # Rasterize it
        rvds = driver.Create('', src_offset[2], src_offset[3], 1,
                             gdal.GDT_Byte)
        rvds.SetGeoTransform(new_gt)
        gdal.RasterizeLayer(rvds, [1], mem_layer, burn_values=[1])
        rv_array = rvds.ReadAsArray()

        # Mask the source data array with our current feature
        # we take the logical_not to flip 0<->1 to get the correct mask effect
        # we also mask out nodata values explictly
        try:
            masked = np.ma.MaskedArray(src_array,
                                       mask=np.logical_or(
                                           src_array == nodata_value,
                                           np.logical_not(rv_array)))

            #print 'feature ID: ',int(feat.GetFID())

            # GET STATISTICS FOR EACH COUNTY
            print 'do something'
            print masked.shape
            #return masked
            values, counts = np.unique(masked, return_counts=True)
            print values, counts
            pixels = counts[0]
            total_pixels_prov = np.ma.count(masked)
            print pixels
            comb = [prov, pixels, total_pixels_prov]

            #county_stats = getStatsCounty(cnty_array = masked, feat=feat)
            stats.append(comb)

            rvds = None
            mem_ds = None
            feat = vlyr.GetNextFeature()

        except np.ma.MaskError:
            # catch MaskError, ignore feature containing no valid corresponding raster data set
            # in my case the the most southern county of hainan is not totally within the raster extent
            print 'feature ID: ', fid, ' maskError, ignore county and lets continue'

            rvds = None
            mem_ds = None
            feat = vlyr.GetNextFeature()

    vds = None
    rds = None
    return stats  #, src_array, rv_array, masked
    def get_transforms(self, sr_virtual, rect, rect_from='virtual'):
        """Retrieve the `to_work` and `to_virtual` conversion functions.

        Parameters
        ----------
        sr_virtual: osr.SpatialReference
        rect: Footprint or extent or None
        rect_from: one of ('virtual', 'work')
        """
        assert rect_from in ['virtual', 'work']

        if self.sr_work is None:
            return None, None

        assert sr_virtual is not None

        to_work = osr.CreateCoordinateTransformation(
            sr_virtual, self.sr_work).TransformPoints
        to_virtual = osr.CreateCoordinateTransformation(
            self.sr_work, sr_virtual).TransformPoints

        to_work = self._make_transfo(to_work)
        to_virtual = self._make_transfo(to_virtual)

        if self.analyse_transformations:
            if rect_from == 'virtual':
                an = srs.Analysis(to_work, to_virtual, rect)
            else:
                an = srs.Analysis(to_virtual, to_work, rect)
            if rect is None:
                pass
            elif isinstance(rect, Footprint):
                if not an.ratio_valid:
                    s = (
                        'Error while checking if on-the-fly reprojection could be performed '
                        'between between Dataset\'s `sr_work` and raster\'s `sr_virtual`. '
                        'Cause: {} (The reprojection is too lossy).\n'
                        'Solutions:\n'
                        '- Pass those tests by reducing `buzz.env.significant`.\n'
                        '- First reproject the raster (using `gdalwarp` for example).\n'
                        '- Bypass those tests by passing `analyse_transformation=False` to the '
                        'Dataset\'s constructor.\n'
                        '- Use smaller coordinates.\n'
                        '- Use different spatial references.\n'
                        '- Avoid reprojections at all.\n'
                        '>>> help(Dataset) # for more informations.').format(
                            an.messages)
                    raise ValueError(s)
            else:
                minx, maxx, miny, maxy = rect
                if minx != maxx and miny != maxy and not an.inverse_valid:
                    s = (
                        'Error while checking if on-the-fly reprojection could be performed '
                        'between between Dataset\'s `sr_work` and vector\'s `sr_virtual`. '
                        'Cause: {} (The reprojection is too lossy).\n'
                        'Solutions:\n'
                        '- Pass those tests by reducing `buzz.env.significant`.\n'
                        '- Bypass those tests by passing `analyse_transformation=False` to the '
                        'Dataset\'s constructor.\n'
                        '- Use smaller coordinates.\n'
                        '- Use different spatial references.\n'
                        '- Avoid reprojections at all.\n'
                        '>>> help(Dataset) # for more informations.').format(
                            an.messages)
                    raise ValueError(s)

        return to_work, to_virtual
Exemplo n.º 26
0
def reproject(*args, **kwargs):
    """Transform coordinates from a source projection to a target projection.

    Call signatures::

        reproject(C, **kwargs)
        reproject(X, Y, **kwargs)
        reproject(X, Y, Z, **kwargs)

    *C* is the np array of source coordinates.
    *X*, *Y* and *Z* specify arrays of x, y, and z coordinate values

    Parameters
    ----------
    C : multidimensional :class:`numpy:numpy.ndarray`
        Array of shape (...,2) or (...,3) with coordinates (x,y) or (x,y,z)
        respectively
    X : :class:`numpy:numpy.ndarray`
        Array of x coordinates
    Y : :class:`numpy:numpy.ndarray`
        Array of y coordinates
    Z : :class:`numpy:numpy.ndarray`
        Array of z coordinates

    Keyword Arguments
    -----------------
    projection_source : osr object
        defaults to EPSG(4326)
    projection_target : osr object
        defaults to EPSG(4326)
    area_of_interest : tuple
        tuple of floats (WestLongitudeDeg, SouthLatitudeDeg, EastLongitudeDeg,
    dfNorthLatitudeDeg), only gdal>=3

    Returns
    -------
    trans : :class:`numpy:numpy.ndarray`
        Array of reprojected coordinates x,y (...,2) or x,y,z (...,3)
        depending on input array.
    X, Y : :class:`numpy:numpy.ndarray`
        Arrays of reprojected x,y coordinates, shape depending on input array
    X, Y, Z: :class:`numpy:numpy.ndarray`
        Arrays of reprojected x,y,z coordinates, shape depending on input array

    Examples
    --------

    See :ref:`/notebooks/georeferencing/wradlib_georef_example.ipynb`.

    """
    if len(args) == 1:
        C = np.asanyarray(args[0])
        cshape = C.shape
        numCols = C.shape[-1]
        C = C.reshape(-1, numCols)
        if numCols < 2 or numCols > 3:
            raise TypeError('Input Array column mismatch '
                            'to %s' % ('reproject'))
    else:
        if len(args) == 2:
            X, Y = (np.asanyarray(arg) for arg in args)
            numCols = 2
        elif len(args) == 3:
            X, Y, Z = (np.asanyarray(arg) for arg in args)
            zshape = Z.shape
            numCols = 3
        else:
            raise TypeError('Illegal arguments to %s' % ('reproject'))

        xshape = X.shape
        yshape = Y.shape

        if xshape != yshape:
            raise TypeError('Incompatible X, Y inputs to %s' % ('reproject'))

        if 'Z' in locals():
            if xshape != zshape:
                raise TypeError('Incompatible Z input to %s' % ('reproject'))
            C = np.concatenate(
                [X.ravel()[:, None],
                 Y.ravel()[:, None],
                 Z.ravel()[:, None]],
                axis=1)
        else:
            C = np.concatenate(
                [X.ravel()[:, None], Y.ravel()[:, None]], axis=1)

    projection_source = kwargs.get('projection_source',
                                   get_default_projection())
    projection_target = kwargs.get('projection_target',
                                   get_default_projection())
    area_of_interest = kwargs.get(
        'area_of_interest',
        (np.float(C[..., 0].min()), np.float(C[..., 1].min()),
         np.float(C[..., 0].max()), np.float(C[..., 1].max())))

    if gdal.VersionInfo()[0] >= '3':
        axis_order = osr.OAMS_TRADITIONAL_GIS_ORDER
        projection_source.SetAxisMappingStrategy(axis_order)
        projection_target.SetAxisMappingStrategy(axis_order)
        options = osr.CoordinateTransformationOptions()
        options.SetAreaOfInterest(*area_of_interest)
        ct = osr.CreateCoordinateTransformation(projection_source,
                                                projection_target, options)
    else:
        ct = osr.CoordinateTransformation(projection_source, projection_target)
    trans = np.array(ct.TransformPoints(C))

    if len(args) == 1:
        # here we could do this one
        # return(np.array(ct.TransformPoints(C))[...,0:numCols]))
        # or this one
        trans = trans[:, 0:numCols].reshape(cshape)
        return trans
    else:
        X = trans[:, 0].reshape(xshape)
        Y = trans[:, 1].reshape(yshape)
        if len(args) == 2:
            return X, Y
        if len(args) == 3:
            Z = trans[:, 2].reshape(zshape)
            return X, Y, Z
    def process_vector(self) -> str:
        try:
            # file_name_with_full_path = r'D:\test\vector_test\石嘴山市-3xq.json'
            # file_main_name = CFile.file_main_name(file_name_with_full_path)
            # file_path = CFile.file_path(file_name_with_full_path)
            xml_obj = self.metadata.metadata_xml()
            # <editor-fold desc="1.空间坐标信息">
            wkt_info = 'POLYGON((${min_x} ${max_y},${max_x} ${max_y},' \
                       '${max_x} ${min_y},${min_x} ${min_y},${min_x} ${max_y}))'
            # 四至坐标
            native_max_x = CUtils.to_decimal(
                xml_obj.get_element_text_by_xpath_one('/TileMetadata/MaxLon'))
            native_max_y = CUtils.to_decimal(
                xml_obj.get_element_text_by_xpath_one('/TileMetadata/MaxLat'))
            native_min_x = CUtils.to_decimal(
                xml_obj.get_element_text_by_xpath_one('/TileMetadata/MinLon'))
            native_min_y = CUtils.to_decimal(
                xml_obj.get_element_text_by_xpath_one('/TileMetadata/MinLat'))
            if (native_max_x is None) or (native_max_y is None) \
                    or (native_min_x is None) or (native_min_y is None):
                native_center_wkt = None
                native_bbox_wkt = None
                geom_native_wkt = None
            else:
                dict_native = {
                    'max_x': CUtils.any_2_str(native_max_x),
                    'max_y': CUtils.any_2_str(native_max_y),
                    'min_x': CUtils.any_2_str(native_min_x),
                    'min_y': CUtils.any_2_str(native_min_y)
                }

                # 中心坐标
                center_x = (native_max_x - native_min_x) / 2 + native_min_x
                center_y = (native_max_y - native_min_y) / 2 + native_min_y
                native_center_wkt = 'POINT({0} {1})'.format(center_x, center_y)

                # 外边框、外包框
                native_bbox_wkt = CUtils.replace_placeholder(
                    wkt_info[:], dict_native)
                geom_native_wkt = native_bbox_wkt

            file_path = self.file_content.work_root_dir
            file_main_name = self.object_name
            native_center_filepath = CFile.join_file(
                file_path, file_main_name + '_native_center.wkt')
            CFile.str_2_file(native_center_wkt, native_center_filepath)
            native_bbox_filepath = CFile.join_file(
                file_path, file_main_name + '_native_bbox.wkt')
            CFile.str_2_file(native_bbox_wkt, native_bbox_filepath)
            native_geom_filepath = CFile.join_file(
                file_path, file_main_name + '_native_geom.wkt')
            CFile.str_2_file(geom_native_wkt, native_geom_filepath)

            projection = xml_obj.get_element_text_by_xpath_one(
                '/TileMetadata/SpatialReference/PRJ')
            if (projection is not None) and (not CUtils.equal_ignore_case(
                    projection, '')):
                source_projection = osr.SpatialReference(wkt=projection)
                source = source_projection.GetAttrValue('GEOGCS', 0)  # 坐标系名称

                prosrs = osr.SpatialReference()
                if prosrs.ImportFromWkt(projection) == gdal.CE_None:
                    proj_wkt = prosrs.ExportToWkt()
                    native_wkt = proj_wkt
                else:
                    native_wkt = projection
                native_proj4 = prosrs.ExportToProj4()
                spatial = None

                rb = (0, 0)
                lu = (0, 0)
                geosrs = prosrs.CloneGeogCS()
                ct = osr.CreateCoordinateTransformation(prosrs, geosrs)
                if ct is not None:
                    rb = ct.TransformPoint(native_max_x, native_max_y)
                    lu = ct.TransformPoint(native_min_x, native_min_y)
                    wgs84_min_x = lu[0]
                    wgs84_max_y = lu[1]
                    wgs84_max_x = rb[0]
                    wgs84_min_y = rb[1]

                    dict_wgs84 = {
                        'max_x': CUtils.any_2_str(wgs84_max_x),
                        'max_y': CUtils.any_2_str(wgs84_max_y),
                        'min_x': CUtils.any_2_str(wgs84_min_x),
                        'min_y': CUtils.any_2_str(wgs84_min_y)
                    }

                    # 中心坐标
                    center_x = (wgs84_max_x - wgs84_min_x) / 2 + wgs84_min_x
                    center_y = (wgs84_max_y - wgs84_min_y) / 2 + wgs84_min_y
                    wgs84_center_wkt = 'POINT({0} {1})'.format(
                        center_x, center_y)

                    # 外边框、外包框
                    wgs84_bbox_wkt = CUtils.replace_placeholder(
                        wkt_info[:], dict_wgs84)
                    wgs84_geom_wkt = wgs84_bbox_wkt

                    wgs84_center_filepath = CFile.join_file(
                        file_path, file_main_name + '_wgs84_center.wkt')
                    CFile.str_2_file(wgs84_center_wkt, wgs84_center_filepath)
                    wgs84_bbox_filepath = CFile.join_file(
                        file_path, file_main_name + '_wgs84_bbox.wkt')
                    CFile.str_2_file(wgs84_bbox_wkt, wgs84_bbox_filepath)
                    wgs84_geom_filepath = CFile.join_file(
                        file_path, file_main_name + '_wgs84_geom.wkt')
                    CFile.str_2_file(wgs84_geom_wkt, wgs84_geom_filepath)
                    # </editor-fold>

                # <editor-fold desc="2.投影信息">
                native_source = CResource.Prj_Source_Data

                # 坐标系
                native_coordinate = None
                # 3度带/6度带
                native_degree = None
                # 投影方式
                native_project = None
                # 带号
                native_zone = None

                # 创建SpatialReference对象,导入wkt信息
                spatial_ref = osr.SpatialReference(wkt=native_wkt)
                if spatial_ref.IsProjected():
                    native_project = spatial_ref.GetAttrValue('PROJECTION')
                    native_coordinate = spatial_ref.GetAttrValue('GEOGCS')
                    # native_degree = spatial_ref.GetAttrValue('GEOGCS|UNIT', 1)
                    native_degree, native_zone = self.get_prj_degree_zone(
                        spatial_ref)
                elif spatial_ref.IsGeocentric():
                    native_project = None
                    native_coordinate = spatial_ref.GetAttrValue('GEOGCS')
                    native_degree = None
                    native_zone = None
                # </editor-fold>

                result = CResult.merge_result(self.Success, '处理完毕!')
                result = CResult.merge_result_info(result, self.Name_Prj_Wkt,
                                                   native_wkt)
                result = CResult.merge_result_info(result, self.Name_Prj_Proj4,
                                                   native_proj4)
                result = CResult.merge_result_info(result,
                                                   self.Name_Prj_Project,
                                                   native_project)
                result = CResult.merge_result_info(result,
                                                   self.Name_Prj_Coordinate,
                                                   native_coordinate)
                result = CResult.merge_result_info(result,
                                                   self.Name_Prj_Source,
                                                   native_source)
                result = CResult.merge_result_info(result, self.Name_Prj_Zone,
                                                   native_zone)
                result = CResult.merge_result_info(result,
                                                   self.Name_Prj_Degree,
                                                   native_degree)
                return result
                # return CResult.merge_result(self.Success, '处理完毕!')
            else:
                return CResult.merge_result(self.Success, '处理完毕!')
        except Exception as error:
            CLogger().warning('矢量数据的空间信息处理出现异常, 错误信息为: {0}'.format(
                error.__str__()))
            return CResult.merge_result(
                self.Failure,
                '矢量数据的空间信息处理出现异常,错误信息为:{0}!'.format(error.__str__()))
Exemplo n.º 28
0
def zonal_stats(vector_path, raster_path, raster_type, fieldname, nodata_value=None, global_src_extent=False):
    rds = gdal.Open(raster_path, GA_ReadOnly)
    assert(rds)
    rb = rds.GetRasterBand(1)
    rgt = rds.GetGeoTransform()

    if nodata_value:
        nodata_value = float(nodata_value)
        rb.SetNoDataValue(nodata_value)

    vds = ogr.Open(vector_path, GA_ReadOnly)  # TODO maybe open update if we want to write stats
    assert(vds)
    vlyr = vds.GetLayer(0)

    # Reproject vector geometry to same projection as raster
    sourceSR = vlyr.GetSpatialRef()
    targetSR = osr.SpatialReference()
    targetSR.ImportFromWkt(rds.GetProjectionRef())
    coordTrans = osr.CreateCoordinateTransformation(sourceSR,targetSR)

    # create an in-memory numpy array of the source raster data
    # covering the whole extent of the vector layer
    if global_src_extent:
        # use global source extent
        # useful only when disk IO or raster scanning inefficiencies are your limiting factor
        # advantage: reads raster data in one pass
        # disadvantage: large vector extents may have big memory requirements
        src_offset = bbox_to_pixel_offsets(rgt, vlyr.GetExtent())
        src_array = rb.ReadAsArray(*src_offset)

        # calculate new geotransform of the layer subset
        new_gt = (
            (rgt[0] + (src_offset[0] * rgt[1])),
            rgt[1],
            0.0,
            (rgt[3] + (src_offset[1] * rgt[5])),
            0.0,
            rgt[5]
        )

    mem_drv = ogr.GetDriverByName('Memory')
    driver = gdal.GetDriverByName('MEM')

    # Loop through vectors
    stats = []
    feat = vlyr.GetNextFeature()
    while feat is not None:

        if not global_src_extent:
            # use local source extent
            # fastest option when you have fast disks and well indexed raster (ie tiled Geotiff)
            # advantage: each feature uses the smallest raster chunk
            # disadvantage: lots of reads on the source raster

            geom = feat.GetGeometryRef()
            # reproject the geometry
            geom.Transform(coordTrans)
            feat.SetGeometry(geom)
            src_offset = bbox_to_pixel_offsets(rgt, feat.geometry().GetEnvelope())
            src_array = rb.ReadAsArray(*src_offset)

            # calculate new geotransform of the feature subset
            new_gt = (
                (rgt[0] + (src_offset[0] * rgt[1])),
                rgt[1],
                0.0,
                (rgt[3] + (src_offset[1] * rgt[5])),
                0.0,
                rgt[5]
            )

        # Create a temporary vector layer in memory
        mem_ds = mem_drv.CreateDataSource('out')
        mem_layer = mem_ds.CreateLayer('poly', None, ogr.wkbPolygon)
        mem_layer.CreateFeature(feat.Clone())

        # Rasterize it
        rvds = driver.Create('', src_offset[2], src_offset[3], 1, gdal.GDT_Byte)
        rvds.SetGeoTransform(new_gt)
        gdal.RasterizeLayer(rvds, [1], mem_layer, burn_values=[1])
        rv_array = rvds.ReadAsArray()

        # Mask the source data array with our current feature
        # we take the logical_not to flip 0<->1 to get the correct mask effect
        # we also mask out nodata values explicitly
        masked = np.ma.MaskedArray(
            src_array,
            mask=np.logical_or(
                src_array == nodata_value,
                np.logical_not(rv_array)
            )
        )

        if raster_type == 'landuse':
            unique, counts = np.unique(masked, return_counts=True)
            unique2 = [str(i) for i in unique.astype(int)]
            count = dict(zip(unique2, counts.astype(int)))
            feature_stats = {
                #'sum': float(masked.sum()),
                fieldname: str(feat.GetField(fieldname))}
            feature_stats.update(count)
        elif raster_type == 'population':
            feature_stats = {
                #'max': float(masked.max()),
                'mean': float(masked.mean()),
                #'count': int(masked.count()),
                #'fid': int(feat.GetFID()),
                fieldname: str(feat.GetField(fieldname))}

        stats.append(feature_stats)        
        
        rvds = None
        mem_ds = None
        feat = vlyr.GetNextFeature()

    vds = None
    rds = None
    return stats
Exemplo n.º 29
0
def CoordinateTransformPoint(longitude, latitude, srs, des):
    transformer = osr.CreateCoordinateTransformation(srs, des)
    coord = transformer.TransformPoint(longitude, latitude)
    return coord[0], coord[1]
Exemplo n.º 30
0
    def transform_to_WGS84(self, geo_transform: tuple, image_size_x: int, image_size_y: int, projection: str) -> CJson:
        """
        wgs84坐标系转换结果(wgs84节点)
        :param geo_transform:
        :param image_size_x:
        :param image_size_y:
        :param projection:
        :return:
        """
        json_wgs84 = CJson()
        spatial_ref = osr.SpatialReference()
        spatial_ref.SetWellKnownGeogCS('WGS84')
        wgs84_wkt = spatial_ref.ExportToWkt()
        wgs84_proj4 = spatial_ref.ExportToProj4()
        spatial_ref.MorphToESRI()
        wgs84_esri = spatial_ref.ExportToWkt()
        json_wgs84_coordinate = CJson()
        json_wgs84_coordinate.set_value_of_name('wkt', wgs84_wkt)
        json_wgs84_coordinate.set_value_of_name('proj4', wgs84_proj4)
        json_wgs84_coordinate.set_value_of_name('esri', wgs84_esri)
        json_wgs84.set_value_of_name('coordinate', json_wgs84_coordinate.json_obj)

        if geo_transform is not None:
            point_left_top_x = geo_transform[0]
            point_left_top_y = geo_transform[3]
            point_right_bottom_x = geo_transform[0] + image_size_x * geo_transform[1] + image_size_y * geo_transform[2]
            point_right_bottom_y = geo_transform[3] + image_size_x * geo_transform[4] + image_size_y * geo_transform[5]
            rb = (0, 0)
            lu = (0, 0)
            if not CUtils.equal_ignore_case(projection, ''):
                source_projection = osr.SpatialReference(wkt=projection)
                source = source_projection.GetAttrValue('GEOGCS', 0)
                prosrs = osr.SpatialReference()
                prosrs.ImportFromWkt(projection)
                geosrs = prosrs.CloneGeogCS()

                if "GetPROJVersionMajor" in dir(osr) and osr.GetPROJVersionMajor() >= 6:  # gdal>=3.0
                    prosrs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
                    geosrs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)

                ct = osr.CreateCoordinateTransformation(prosrs, geosrs)
                if ct is not None:
                    rb = ct.TransformPoint(point_right_bottom_x, point_right_bottom_y)
                    lu = ct.TransformPoint(point_left_top_x, point_left_top_y)

                    json_bounding = CJson()
                    json_bounding.set_value_of_name('left', lu[0])
                    json_bounding.set_value_of_name('top', lu[1])
                    json_bounding.set_value_of_name('right', rb[0])
                    json_bounding.set_value_of_name('bottom', rb[1])
                    json_wgs84.set_value_of_name('boundingbox', json_bounding.json_obj)
                    json_wgs84.set_value_of_name('msg', 'boundingbox四至范围从{0}坐标系转wgs_84坐标系转换成功!'.format(source))
                    json_wgs84.set_value_of_name('result', self.Success)
                else:
                    json_wgs84.set_value_of_name('msg',
                                                 'boundingbox四至范围从{0}坐标系转wgs_84坐标系转换失败!失败原因:构建坐标转换关系失败!可能是地方坐标系,无法转换。'.format(
                                                     source))
                    json_wgs84.set_value_of_name('result', self.Failure)
            else:
                json_wgs84.set_value_of_name('msg',
                                             'boundingbox四至范围从原坐标系转wgs_84坐标系转换失败!失败原因:文件不存在coordinate信息!')
                json_wgs84.set_value_of_name('result', self.Failure)
        else:
            json_wgs84.set_value_of_name('msg',
                                         'boundingbox四至范围从原坐标系转wgs_84坐标系转换失败!失败原因:文件不存在仿射变换信息!')
            json_wgs84.set_value_of_name('result', self.Failure)
        return json_wgs84