search
HomeBackend DevelopmentPython Tutorialpython gdal tutorial: geometry and projection
python gdal tutorial: geometry and projectionDec 24, 2016 pm 04:01 PM
gdalgeometry

Create an empty geometry object: ogr.Geometry

The methods used to define various geometries are different (point, line, polygon, etc)

To create a new point, use the method AddPoint( , < ;y>, []). The z coordinate is generally omitted, and the default value is 0

For example:

point = ogr.Geometry(ogr.wkbPoint)

point.AddPoint(10,20)

New line

Use AddPoint(, , []) to add a point

Use SetPoint(, , , []) to change the coordinates of a point

For example, the following code changes the coordinates of point 0:

line = ogr.Geometry(ogr.wkbLineString)

line.AddPoint(10,10)

line.AddPoint(20,20)

line. SetPoint(0,30,30) #(10,10) -> (30,30)

Count the number of all points

print line.GetPointCount()

Read the x coordinate and y coordinate of point 0

print line.GetX(0)

print line.GetY(0)

To create a new polygon, first create a new ring, and then add the ring to the polygon object.

How to create a ring? First create a new ring object, and then add points to it one by one.

ring = ogr.Geometry(ogr.wkbLinearRing)

ring.AddPoint(0,0)

ring.AddPoint(100,0)

ring.AddPoint(100,100)

ring.AddPoint(0,100)

At the end, use CloseRings to close the ring, or set the coordinates of the last point to be the same as the first point.

ring.CloseRings()

ring.AddPoint(0,0)

The following is an example to create a box. This is a polygon object, composed of two layers of rings. Outring = OGR.Geometry (OGR.WKBLINEARING)

Outring.addpoint (0,0). ) outring.AddPoint(0,0)

inring = ogr.Geometry(ogr.wkbLinearRing)inring = ogr.Geometry(ogr.wkbLinearRing)

inring.AddPoint(25,25)

inring.AddPoint(75,25)

inring.AddPoint(75,75)

inring.AddPoint(25,75)

inring.CloseRings()

polygon = ogr.Geometry(ogr.wkbPolygon)

polygon.AddGeometry(outring)

polygon .AddGeometry(inring)

The last three sentences are more important, that is, first create a polygon object, and then add the outer ring and inner ring

The following sentence can help you count how many rings your polygon can have

print polygon.GetGeometryCount()

Read ring from polygon, the order of index is the same as the order of adding ring when creating polygon

outring = polygon.GetGeometryRef(0)

inring = polygon.GetGeometryRef(1)

Create multi geometry

such as MultiPoint, MultiLineString, MultiPolygon

Use AddGeometry to add ordinary geometric shapes to the composite geometry, for example:

multipoint = ogr.Geometry(ogr.wkbMultiPoint)

point = ogr. Geometry(ogr.wkbPoint)point = ogr.Geometry(ogr.wkbPoint)

point.AddPoint(10,10)

multipoint.AddGeometry(point)

point.AddPoint(20,20)

multipoint.AddGeometry( point)

Reading Geometry in MultiGeometry is the same as reading ring from Polygon. It can be said that Polygon is a built-in MultiGeometry.

Don’t delete an existing Feature’s Geometry, it will crash python.

You can only delete the Geometry created during the running of the script, for example, manually created, or automatically created by calling other functions. Even if this Geometry has been used to create other Features, you can still delete it.

For example: Polygon.Destroy()

Regarding projection Projections, use SpatialReference object

A variety of Projections, GDAL supports WKT, PROJ.4, ESPG, USGS, ESRI.prj

can be read from layer and Geometry Get Projections, for example:

spatialRef = layer.GetSpatialRef()

spatialRef = geom.GetSpatialReference()

Projection information is generally stored in the .prj file. If there is no such file, the above function returns None

Create a new one Projection:

First import the osr library, then use osr.SpatialReference() to create a SpatialReference object

Then use the following statements to import the projection information to the SpatialReference object

  •ImportFromWkt()

  •ImportFromEPSG( ; ;)

 •ImportFromUSGS(, )

•ImportFromXML()

Export Projection, use the following statement to export it as a string

​ •ExportToWkt()

​ •ExportToPrettyWkt()

​ •ExportToPro​ j4()

  •ExportToPCI()

  •ExportToUSGS()

•ExportToXML()

To perform projection transformation on a geometric shape Geometry, you must first initialize two Projections, then create a CoordinateTransformation object and use it for transformation

sourceSR = osr.SpatialReference()

sourceSR.ImportFromEPSG(32612) #UTM 12N WGS84

targetSR = osr.SpatialReference()

targetSR.ImportFromEPSG(4326) #Geo WGS84

coordTrans = osr.CoordinateTransformation(sourceSR, targetSR)

geom.Transform(coordTrans)

But this code is very annoying ! It doesn't work in windows. There is a discussion in the foreigner's forum, saying that there is no problem in Linux, but Windows is dead, hehe. . .

There are a few more things to pay attention to:

Edit the Geometry at the appropriate time. It is best not to move it after the projection transformation.

To perform projection transformation on all Geometry in a DataSource, you have to do it one by one. Use a loop.

Writing your projection into a .prj file is actually very simple. First, MorphToESRI(), convert it into a string, then open a text file and write it in it. For example:

targetSR.MorphToESRI()

file = open('test.prj', 'w')

file.write(targetSR.ExportToWkt())

ffile.close()

The above is python gdal Tutorial: Geometry and projection content. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Use Python to Find the Zipf Distribution of a Text FileHow to Use Python to Find the Zipf Distribution of a Text FileMar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Image Filtering in PythonImage Filtering in PythonMar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How to Work With PDF Documents Using PythonHow to Work With PDF Documents Using PythonMar 02, 2025 am 09:54 AM

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

How to Cache Using Redis in Django ApplicationsHow to Cache Using Redis in Django ApplicationsMar 02, 2025 am 10:10 AM

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

How to Implement Your Own Data Structure in PythonHow to Implement Your Own Data Structure in PythonMar 03, 2025 am 09:28 AM

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Introduction to Parallel and Concurrent Programming in PythonIntroduction to Parallel and Concurrent Programming in PythonMar 03, 2025 am 10:32 AM

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor