More

Wrong coordinates after Usage of NumPyArrayToRaster(… )

Wrong coordinates after Usage of NumPyArrayToRaster(… )


My Project I am currently working at should enable cellvalue manipulation on raster files using ArcPy. My Script works fine except I am not getting the right Y-Values (northing values) for the modified raster image. I will show you my code:

# Import arcpy module import arcpy # Check out any necessary licenses arcpy.CheckOutExtension("3D") # Local variables: inputRaster = r'G:Datafilegdb.gdbClipRaster2' firstCoord = "33321792 6012729" secondCoord = "33321809 6012763" level = "5" outputRaster = r'G:Datafilegdb.gdbRasterModTestData2' # Get Raster Description: desc = arcpy.Describe(inputRaster) xmin = desc.extent.XMin xmax = desc.extent.XMax ymin = desc.extent.YMin ymax = desc.extent.YMax cellsize = desc.meanCellWidth nodata = desc.noDataValue sr = desc.SpatialReference lowerleft = arcpy.Point(xmin,ymin) xwert1 = firstCoord.split(" ") UTMRechts1 = float(xwert1[0]) UTMHoch1 = float(xwert1[1]) xwert2 = secondCoord.split(" ") UTMRechts2 = float(xwert2[0]) UTMHoch2 = float(xwert2[1]) # Converts the Raster to a NumPyArray raster = arcpy.Raster(inputRaster) array = arcpy.RasterToNumPyArray(raster,nodata_to_value=raster.minimum) # Loop through the NumPy-Array and check if the point is inside the bounding rectangle i = ymin countX = 0 while i < ymax: j = xmin countY = 0 while j < xmax: if (j >= UTMRechts1 and j <= UTMRechts2 and i >= UTMHoch1 and i <= UTMHoch2): array[countX,countY] += int(level) countY += 1 j += cellsize countX += 1 i += cellsize newraster = arcpy.NumPyArrayToRaster(array, lowerleft, cellsize, cellsize, nodata) arcpy.DefineProjection_management(newraster, sr) if arcpy.Exists(outputRaster): arcpy.Delete_management(outputRaster) newraster.save(outputRaster)

As You can see, the area bounding by a rectangle (lower left: 33321792 6012729, upper right: 33321809 6012763 //UTM 33N (ETRS89) ) should be modified with raise of its elevation by 5 metres. The following screenshot shows a extract from the result raster:

Unfortunately, the lower left corner of the modified area is at (33321792 6012708 metres UTM33N/ETRS89) and the upper right corner is at (33321809 6012743 metres UTM33N/ETRS89). So the easting of the coordinate fits perfectly to the requested extent, but the northing is displaced by about 21 metres to the south. The input raster has one band, a cellsize of 0.5 m and 2254 columns and 2532 rows.

Additional Info: If I print the coordinates which are inside the bounding box, the values I want to have show up. So I guess, the mistake is in the retransformation from NumpyArray to the raster file. Has anyone experience with this problem?

Can anybody help me what to do to get the correct extent of the modified area or show me the mistake in my code?


I solved my Problem on my own. The Problem is, that the Retransformation to the NumpyArray starts filling the array at array[0,0] on the top-left corner. So I updated my while-loop:

i = ymax countX = 0 while i >= ymin: j = xmin countY = 0 while j <= xmax: if (j >= UTMRechts1 and j <= UTMRechts2 and i >= UTMHoch1 and i <= UTMHoch2): array[zaehlerX,zaehlerY] += int(level) countY += 1 j += cellsize countX += 1 i -= cellsize

As you can see, I "count" from the maximum Northing-value to the minimum value. In this case, I get the right position of the modified area.


Mdhntd

What verb for taking advantage fits in "I don't want to ________ on the friendship"?

How did they film the Invisible Man being invisible in 1933?

Why are symbols not written in words?

Would skyscrapers tip over if people fell sideways?

Is this house-rule removing the increased effect of cantrips at higher character levels balanced?

Active wildlife outside the window- Good or Bad for Cat psychology?

The alcoholic village festival

Automorphisms and epimorphisms of finite groups

Why doesn't SpaceX land boosters in Africa?

Subset of knight's move in chess.

What was the first science fiction or fantasy multiple choice book?

Position representation of spin states and spin operators

How does mmorpg store data?

How does the 'five minute adventuring day' affect class balance?

Is it possible to alias a column based on the result of a select+where?

Is it advisable to inform the CEO about his brother accessing his office?

Does a lens with a bigger max. aperture focus faster than a lens with a smaller max. aperture?

Is it OK to say "The situation is pregnant with a crisis"?

What happens if a caster is surprised while casting a spell with a long casting time?

Calculus, water poured into a cone: Why is the derivative non-linear?

How to save raster with projection into Python

Transforming a image to a shape defined by image corners in earth coordinates - PythonAre there limitations using a PostGIS out-db raster?Problem editing raster and saving with projection and transformation intactPython GDAL: Save array as raster with projection from other fileGDAL (Python) Aggregate Raster Into Lower ResolutionImage processing using Python, GDAL and Scikit-ImageASCII coordinates to geographic coordinates with GDAL?How to map Albers projection raster in Basemap of python?Save multiband raster with gdalGDAL, python: How to create a GDAL dataset object from a numpy arrayHow to save numpy array as single band image?

I applied a raster processing that is already in a known coordinate system with this code,

but when I save my raster at the end of this script, I get a non-georeferenced TIFF raster

How can I keep the same coordinate system of the initial raster (without tranforming the output raster into local coordinates)

Since I am new to Python, and I have no knowledge of Python, i would like someone to correct me my script please.

You cannot georeference a raster with Opencv. You need to use a geospatial module as GDAL or rasterio

i have installed GDAL but i dont know how to use the command, can you give me the correcte script please?

Transforming a image to a shape defined by image corners in earth coordinates - Python for example

I applied a raster processing that is already in a known coordinate system with this code,

but when I save my raster at the end of this script, I get a non-georeferenced TIFF raster

How can I keep the same coordinate system of the initial raster (without tranforming the output raster into local coordinates)

Since I am new to Python, and I have no knowledge of Python, i would like someone to correct me my script please.

You cannot georeference a raster with Opencv. You need to use a geospatial module as GDAL or rasterio

i have installed GDAL but i dont know how to use the command, can you give me the correcte script please?

Transforming a image to a shape defined by image corners in earth coordinates - Python for example

I applied a raster processing that is already in a known coordinate system with this code,

but when I save my raster at the end of this script, I get a non-georeferenced TIFF raster

How can I keep the same coordinate system of the initial raster (without tranforming the output raster into local coordinates)

Since I am new to Python, and I have no knowledge of Python, i would like someone to correct me my script please.

I applied a raster processing that is already in a known coordinate system with this code,

but when I save my raster at the end of this script, I get a non-georeferenced TIFF raster

How can I keep the same coordinate system of the initial raster (without tranforming the output raster into local coordinates)

Since I am new to Python, and I have no knowledge of Python, i would like someone to correct me my script please.

You cannot georeference a raster with Opencv. You need to use a geospatial module as GDAL or rasterio

i have installed GDAL but i dont know how to use the command, can you give me the correcte script please?

Transforming a image to a shape defined by image corners in earth coordinates - Python for example

You cannot georeference a raster with Opencv. You need to use a geospatial module as GDAL or rasterio

i have installed GDAL but i dont know how to use the command, can you give me the correcte script please?

Transforming a image to a shape defined by image corners in earth coordinates - Python for example

You cannot georeference a raster with Opencv. You need to use a geospatial module as GDAL or rasterio

You cannot georeference a raster with Opencv. You need to use a geospatial module as GDAL or rasterio

i have installed GDAL but i dont know how to use the command, can you give me the correcte script please?

i have installed GDAL but i dont know how to use the command, can you give me the correcte script please?

Transforming a image to a shape defined by image corners in earth coordinates - Python for example

Transforming a image to a shape defined by image corners in earth coordinates - Python for example


矢量数据源对象¶

DataSource ¶

DataSource is a wrapper for the OGR data source object that supports reading data from a variety of OGR-supported geospatial file formats and data sources using a consistent interface. Each data source is represented by a DataSource object which contains one or more layers of data. Each layer, represented by a Layer object, contains some number of geographic features ( Feature ), information about the type of features contained in that layer (e.g. points, polygons, etc.), as well as the names and types of any additional fields ( Field ) of data that may be associated with each feature in that layer.

The constructor for DataSource only requires one parameter: the path of the file you want to read. However, OGR also supports a variety of more complex data sources, including databases, that may be accessed by passing a special name string instead of a path. For more information, see the OGR Vector Formats documentation. The name property of a DataSource instance gives the OGR name of the underlying data source that it is using.

The optional encoding parameter allows you to specify a non-standard encoding of the strings in the source. This is typically useful when you obtain DjangoUnicodeDecodeError exceptions while reading field values.

Once you've created your DataSource , you can find out how many layers of data it contains by accessing the layer_count property, or (equivalently) by using the len() function. For information on accessing the layers of data themselves, see the next section:

Returns the number of layers in the data source.

Returns the name of the data source.

Layer ¶

Layer is a wrapper for a layer of data in a DataSource object. You never create a Layer object directly. Instead, you retrieve them from a DataSource object, which is essentially a standard Python container of Layer objects. For example, you can access a specific layer by its index (e.g. ds[0] to access the first layer), or you can iterate over all the layers in the container in a for loop. The Layer itself acts as a container for geometric features.

Typically, all the features in a given layer have the same geometry type. The geom_type property of a layer is an OGRGeomType that identifies the feature type. We can use it to print out some basic information about each layer in a DataSource :

The example output is from the cities data source, loaded above, which evidently contains one layer, called "cities" , which contains three point features. For simplicity, the examples below assume that you've stored that layer in the variable layer :

Returns the name of this layer in the data source.

Returns the number of features in the layer. Same as len(layer) :

Returns the geometry type of the layer, as an OGRGeomType object:

Returns the number of fields in the layer, i.e the number of fields of data associated with each feature in the layer:

Returns a list of the names of each of the fields in this layer:

Returns a list of the data types of each of the fields in this layer. These are subclasses of Field , discussed below:

Returns a list of the maximum field widths for each of the fields in this layer:

Returns a list of the numeric precisions for each of the fields in this layer. This is meaningless (and set to zero) for non-numeric fields:

Returns the spatial extent of this layer, as an Envelope object:

Property that returns the SpatialReference associated with this layer:

If the Layer has no spatial reference information associated with it, None is returned.

Property that may be used to retrieve or set a spatial filter for this layer. A spatial filter can only be set with an OGRGeometry instance, a 4-tuple extent, or None . When set with something other than None , only features that intersect the filter will be returned when iterating over the layer:

A method that returns a list of the values of a given field for each feature in the layer:

A method that returns a list containing the geometry of each feature in the layer. If the optional argument geos is set to True then the geometries are converted to GEOSGeometry objects. Otherwise, they are returned as OGRGeometry objects:

Returns a boolean indicating whether this layer supports the given capability (a string). Examples of valid capability strings include: 'RandomRead' , 'SequentialWrite' , 'RandomWrite' , 'FastSpatialFilter' , 'FastFeatureCount' , 'FastGetExtent' , 'CreateField' , 'Transactions' , 'DeleteFeature' , and 'FastSetNextByIndex' .

Feature ¶

Feature wraps an OGR feature. You never create a Feature object directly. Instead, you retrieve them from a Layer object. Each feature consists of a geometry and a set of fields containing additional properties. The geometry of a field is accessible via its geom property, which returns an OGRGeometry object. A Feature behaves like a standard Python container for its fields, which it returns as Field objects: you can access a field directly by its index or name, or you can iterate over a feature's fields, e.g. in a for loop.

Returns the geometry for this feature, as an OGRGeometry object:

A method that returns the value of the given field (specified by name) for this feature, not a Field wrapper object:

Returns the type of geometry for this feature, as an OGRGeomType object. This will be the same for all features in a given layer and is equivalent to the Layer.geom_type property of the Layer object the feature came from.

Returns the number of fields of data associated with the feature. This will be the same for all features in a given layer and is equivalent to the Layer.num_fields property of the Layer object the feature came from.

Returns a list of the names of the fields of data associated with the feature. This will be the same for all features in a given layer and is equivalent to the Layer.fields property of the Layer object the feature came from.

Returns the feature identifier within the layer:

Returns the name of the Layer that the feature came from. This will be the same for all features in a given layer:

A method that returns the index of the given field name. This will be the same for all features in a given layer:

Field ¶

Returns the name of this field:

Returns the OGR type of this field, as an integer. The FIELD_CLASSES dictionary maps these values onto subclasses of Field :

Returns a string with the name of the data type of this field:

Returns the value of this field. The Field class itself returns the value as a string, but each subclass returns the value in the most appropriate form:

Returns the width of this field:

Returns the numeric precision of this field. This is meaningless (and set to zero) for non-numeric fields:

Returns the value of the field as a double (float):

Returns the value of the field as an integer:

Returns the value of the field as a string:

Returns the value of the field as a tuple of date and time components:

Driver ¶

The Driver class is used internally to wrap an OGR DataSource driver.

Returns the number of OGR vector drivers currently registered.


Data Tip - Object names

To improve code readability, file and object names should be used that make it clear what is in the file. The data for this episode were collected from Harvard Forest so we’ll use a naming convention of datatype_HARV .

After viewing the attributes of our raster, we can examine the raw values of the array with .values :

This can give us a quick view of the values of our array, but only at the corners. Since our raster is loaded in python as a DataArray type, we can plot this in one line similar to a pandas DataFrame with DataArray.plot() .

Nice plot! Notice that rioxarray helpfully allows us to plot this raster with spatial coordinates on the x and y axis (this is not the default in many cases with other functions or libraries).

This map shows the elevation of our study site in Harvard Forest. From the legend, we can see that the maximum elevation is

400, but we can’t tell whether this is 400 feet or 400 meters because the legend doesn’t show us the units. We can look at the metadata of our object to see what the units are. Much of the metadata that we’re interested in is part of the CRS, and it can be accessed with .rio.crs . We introduced the concept of a CRS in an earlier episode.

Now we will see how features of the CRS appear in our data file and what meanings they have.

View Raster Coordinate Reference System (CRS) in Python

We can view the CRS string associated with our Python object using the crs attribute.

To just print the EPSG code number as an int , we use the .to_epsg() method:

EPSG codes are great for succinctly representing a particular coordinate reference system. But what if we want to see information about the CRS? For that, we can use pyproj , a library for representing and working with coordinate reference systems.

The CRS class from the pyproj library allows us to create a CRS object with methods and attributes for accessing specific information about a CRS, or the detailed summary shown above.

A particularly useful attribute is area_of_use , which shows the geographic bounds that the CRS is intended to be used.


Motivation¶

In this tutorial, we go through a very practical example that relates to our daily commute: Where is the closest public transport stop from my place of living? Hence, our aim is to search for each building in Helsinki Region (around 159 000 buildings) the closest public transport stop (

8400 stops). The building points have been fetched from OpenStreetMap using a library called OSMnx (we will learn more about this library later), and the public transport stops have been fetched from open GTFS dataset for Helsinki Region that contains information about public transport stops, schedules etc.


Quis custodiet ipsos custodes?

If you program in Python, then the Python binding to the Geospatial Data Abstraction library (GDAL) and Numpy are indispensable tools for reading, writing and manipulating raster image in GeoTIFF format.

This summarizes my brief experience working with them.

A GeoTIFF image file may contain one or more bands. Each band can be viewed as a separate 2D data array but every band in the same file will have the same array dimension (or shape, in Numpy lingo).

All image pixels in a band (data element of array) are of the same data type, e.g. byte, int16, etc., but one band may be of different data type from another in the same file.

By convention, if a GeoTIFF file contains a RGB raster image, it will have 3 bands (4 if it is RGBA, with the addition of alpha channel for pixel transparency) of byte data — band 1 for red, 2 for green and 3 for blue.

GDAL API

To read GeoTIFF metadata (georeference information)

GeoTransform() returns a tuple where (X, Y) are corner coordinates of the image indicating the origin of the array, i.e. data element[0,0]. But, which corner?

If deltaX is positive, X is West. Otherwise, X is East. If deltaY is positive, Y is South. Otherwise, Y is North. In other words, when both deltaX and deltaY is positive, (X, Y) is the lower-left corner of the image.

It is also common to have positive deltaX but negative deltaY which indicates that (X, Y) is the top-left corner of the image.

There are several standard notations for SRS, e.g. WKT, Proj4, etc. GetProjection() returns a WKT string. The meaning and unit-of-measurement for X, Y, deltaX and deltaY are based on the spatial reference system (SRS) of the image. For example, if the SRS is Stereographic projection, they are in kilometres.

To convert from WKT notation to Proj4

To load a multi-band GeoTIFF image file as Numpy arrays

Unlike mathematical convention for coordinates (X, Y), Numpy array indexing uses [y-offset][x-offset].

To save a 2-D Numpy array as 1-band GeoTIFF file

Included correction from Pete

To slice from a bigger image (array)

To change coordinates from one SRS to another

Use pyproj
For example, to convert 2 lists of longitudes and latitudes to X, Y coordinates in polar stereographic projection:


Version 1.4.0¶

Profile distances are now returned in projected (Cartesian) coordinates by the profile method of gridders if a projection is given. The method has the option to apply a projection to the coordinates before predicting so we can pass geographic coordinates to Cartesian gridders. In these cases, the distance along the profile is calculated by the profile_coordinates function with the unprojected coordinates (in the geographic case it would be degrees). The profile point calculation is also done assuming that coordinates are Cartesian, which is clearly wrong if inputs are longitude and latitude. To fix this, we now project the input points prior to passing them to profile_coordinates . This means that the distances are Cartesian and generation of profile points is also Cartesian (as is assumed by the function). The generated coordinates are projected back so that the user gets longitude and latitude but distances are still projected Cartesian meters. (#231)


Multiply the world matrix by the object-space vector for world space coordinate:

`Object.matrix_world is a 4x4 transformation matrix. It contains translation, rotation and scale. A 4x4 matrix can also be used for mirroring and shearing (not covered in my answer).

The translation is stored in the first 3 rows of the 4th column of the matrix ( d , h , l ):

Rotation and scale are sort of combined. The rotation is stored in a , b , c , e , f , g , i , j and k . The scale is stored in a , f and k . The values in a , f and k of the rotation are taken and multiplied by the scale factor to store both pieces of information.

To get only the rotation, you need to normalize the 3x3 matrix:

To get only the scale, you can use the utility method:

Or manually, normalize the matrix and divide each of the un-normalized by the normalized components ( a , f , k ):

If you need the world coordinates of all vertices, it's more efficient to use the transform() method:

It will apply the transformation matrix to the mesh, so multiply the world matrix with all vertex coordinates. You may wonder about the change in orientation of a mesh object in viewport if you do the above. It can be fixed by resetting the matrix_world (otherwise the transformation will be done twice):


Survey coordinate system

Use the survey coordinate system to identify the specific location on the earth's surface where your Revit model resides. This coordinate system is defined outside the context of a project.

Many survey coordinate systems are standardized. Some systems use latitude and longitude others use XYZ coordinates. Survey coordinate systems handle significantly larger scales than project coordinate systems and deal with issues such as the curvature of the earth and terrain, which are insignificant to project coordinate systems.

In Revit , the survey point identifies a real-world location near the model. For example, you can place the survey point at a corner of the project site or at the intersection of 2 property lines, and specify its real-world coordinates. (See in the above image.)

The survey coordinate system is synonymous with the following terms used by other software applications or in other contexts:

  • global coordinates
  • GIS coordinates
  • grid coordinates
  • surveyor coordinates
  • projection coordinates
  • state plane
  • shared coordinates

1 Answer 1

There is nothing wrong with your data, your main mistake is that you need to pay attention to the plot function used. This link tells you how to plot your data. https://matplotlib.org/tutorials/introductory/pyplot.html

However I would change the last line to something like:

In general is a bit difficult to understand what exactly you want or the format of the data, so I hope this works. Follow the tutorial it will help you understand what you really need to continue.