SlideShare una empresa de Scribd logo
1 de 16
Descargar para leer sin conexión
GEOGRAPHIC SCRIPTING IN GVSIG
HALFWAY BETWEEN USER AND DEVELOPER
Geoinformation Research Group,
Department of Geography
University of Potsdam
21-25 November 2016
Andrea Antonello
PART 5: RASTER DATA
RASTER DATA
Raster data can usually be seen as 2 main types: imagery (ex. ortofoto)
and physical data (ex. elevation model).
While imagery is something you mostly use as nice background data, with
an elevation model there are tons of analyses one can do.
In this document we will mostly refer to raster as the latter case.
Loading raster data in a view is quite simple:
rasters = [
"/home/hydrologis/data/potsdam/dsm_test.asc",
"/home/hydrologis/data/potsdam/dtm_test.asc"
]
epsg = "EPSG:32632"
newview = currentProject().createView("Raster view")
newview.setProjection(getCRS(epsg))
newview.showWindow()
for raster in rasters:
loadRasterFile(raster)
GET RASTER METADATA
To work with raster data it is necessary to get some metadata first.
The most used are: rows and cols, boundaries, resolution, bands
dtmLayer = currentView().getLayer("dtm_test")
print "Raster information: "
print "=============================="
print "Columns:", dtmLayer.getWidth()
print "Rows:", dtmLayer.getHeight()
print "NoData value:", dtmLayer.getNoDataValue().getValue()
print "Resolution:", dtmLayer.cellSize
print "Bands count: ", dtmLayer.getBandsCount()
print "Bounds:"
print " north: ", dtmLayer.maxX
print " south: ", dtmLayer.minX
print " west: ", dtmLayer.minY
print " east: ", dtmLayer.maxY
# values can be read through the getData(band, row, column) method
print "Random value: ", dtmLayer.getData(0, 10, 10)
THE SIMPLEST RASTER ANALYSIS
We now have all the necessary info to loop through the raster data and
calculate max, min, average and valid cells
dtmLayer = currentView().getLayer("dtm_small")
count = 0
sum = 0
min = 10000000 # initialize to something high
max = 0 # initialize to something low
cols = int(dtmLayer.getWidth())
rows = int(dtmLayer.getHeight())
novalue = -9999.0
# now loop over rows and columns
for row in range(0, rows):
if row % 10 == 0: print row, " of ", rows, " are done"
for col in range(0, cols):
value = dtmLayer.getData(0, row, col)
if value != novalue: # active cells are only the valid ones
count += 1
sum += value
if value > max: max = value
if value < min: min = value
avg = sum/count
print "nnMax elevation: ", max
print "Min elevation: ", min
print "Average elevation: ", avg
print "Valid cells: %i of %i" % (count, cols*rows)
PUTTING THE RASTER MIN/MAX IN A SHAPEFILE
Let's put together what we learned until now to extract the position of
the max and min elevation of the raster and place it in a shapefile. Most of
the first part is the same as the simple min/max/avg example seen before.
In order to put the points in a shapefile we will need the positions. A
simple way to get them, is to start in the center of the first cell of the
col/row and move pixel by pixel incrementing the X/Y coordinates:
cellSize = dtmLayer.cellSize
runningY = dtmLayer.maxY - dtmLayer.cellSize / 2.0
for row in xrange(0, rows):
runningX = dtmLayer.minX + dtmLayer.cellSize / 2.0
for col in xrange(0, cols):
value = dtmLayer.getData(0, row, col)
# max/min calculation here
runningX += cellSize
runningY -= cellSize
PUTTING THE RASTER MIN/MAX IN A SHAPEFILE
The whole piece will look like:
dtmLayer = currentView().getLayer("dtm_small")
count = 0; sum = 0
min = 10000000; minX = 0; minY = 0
max = 0; maxX = 0; maxY = 0
cols = dtmLayer.getWidth()
rows = dtmLayer.getHeight()
novalue = -9999.0
cellSize = dtmLayer.cellSize
runningY = dtmLayer.maxY - dtmLayer.cellSize / 2.0
for row in xrange(0, rows):
runningX = dtmLayer.minX + dtmLayer.cellSize / 2.0
for col in xrange(0, cols):
value = dtmLayer.getData(0, row, col)
if value != novalue:
count += 1
sum += value
if value > max:
max = value
maxX = runningX
maxY = runningY
if value < min:
min = value
minX = runningX
minY = runningY
runningX += cellSize
runningY -= cellSize
PUTTING THE RASTER MIN/MAX IN A SHAPEFILE
Now that we have positions and values, we can create the shapefile:
schema = createFeatureType()
schema.append("name", "STRING", 20)
schema.append("value", "DOUBLE", 8)
schema.append("x", "DOUBLE", 8)
schema.append("y", "DOUBLE", 8)
schema.append("GEOMETRY", "GEOMETRY")
schema.get("GEOMETRY").setGeometryType(POINT, D2)
shape = createShape(schema, prefixname="min_max", CRS="EPSG:3003")
and insert the data:
shape.edit()
minPoint = createPoint2D(minX, minY)
shape.append(name='MIN', value=min, x=minX, y=minY, GEOMETRY=minPoint)
maxPoint = createPoint2D(maxX, maxY)
shape.append(name='MAX', value=max, x=maxX, y=maxY, GEOMETRY=maxPoint)
shape.commit()
currentView().addLayer(shape)
PUTTING THE RASTER MIN/MAX IN A SHAPEFILE
and since we are at it, let's add some style:
pointsLegend = shape.getLegend()
pointSymbol = simplePointSymbol()
pointSymbol.setSize(15);
pointSymbol.setColor(Color.BLUE);
pointSymbol.setStyle(3);
pointsLegend.setDefaultSymbol(pointSymbol)
shape.setLegend(pointsLegend)
which should then produce
something like:
CREATING A NEW ARC/INFO ASCII GRID
The Arc/Info ASCII Grid raster format is quite simple to understand.
The file starts with a header:
NCOLS 355 # number of columns
NROWS 361 # number of rows
XLLCORNER 1637140.0 # x coordinate of the lower left corner
YLLCORNER 5110830.0 # y coordinate of the lower left corner
CELLSIZE 10.0 # size of the cell or resolution
NODATA_VALUE -9999 # novalue placeholder
and after that, the data - space separated - are inserted row by row.
First, prepare the input and output data:
# open the new file in write mode
newRasterPath = "/home/hydrologis/data/potsdam_data/dtm_small_1400_1600.asc"
newRasterFile = open(newRasterPath, "w")
# get the start raster
dtmLayer = currentView().getLayer("dtm_small")
cols = dtmLayer.getWidth()
rows = dtmLayer.getHeight()
novalue = -9999.0
CREATING A NEW ASC RASTER
We have all the information to write the header:
newRasterFile.write("NCOLS " + str(cols))
newRasterFile.write("nNROWS " + str(rows))
newRasterFile.write("nXLLCORNER " + str(dtmLayer.minX))
newRasterFile.write("nYLLCORNER " + str(dtmLayer.minY))
newRasterFile.write("nCELLSIZE " + str(dtmLayer.cellSize))
newRasterFile.write("nNODATA_VALUE " + str(novalue))
Then loop through all the values and filter away the ones outside our
range, i.e. set them to novalue:
for row in xrange(0, rows):
newRasterFile.write("n")
for col in xrange(0, cols):
value = dtmLayer.getData(0, row, col)
if value != novalue and value > 1400 and value < 1600:
newRasterFile.write(str(value) + " ")
else:
newRasterFile.write(str(novalue) + " ")
newRasterFile.close()
loadRasterFile(newRasterPath)
CREATING A NEW ASC RASTER
The result, overlayed in greyscale on the original dtm, should look like:
NEIGHBOUR OPERATIONS: EXTRACT PITS
A pit is a cell in the raster that is lower in elevation than its surrounding
cells. Pits are important in hydrology, since "programmatically speaking",
the water doesn't flow out of those pits.
Let's start by creating the shapefile that will hold the pit points and put it
in editing mode:
schema = createFeatureType()
schema.append("value", "DOUBLE", 8)
schema.append("GEOMETRY", "GEOMETRY")
schema.get("GEOMETRY").setGeometryType(POINT, D2)
shape = createShape(schema, prefixname="pits", CRS="EPSG:3003")
shape.edit()
and gather the usual information about the raster:
# get necessary info from layer
dtmLayer = currentView().getLayer("dtm_small")
cols = dtmLayer.getWidth()
rows = dtmLayer.getHeight()
novalue = -9999.0
NEIGHBOUR OPERATIONS: EXTRACT PITS
The core part loops through the raster values and looks for cells with
higher elevation values around them:
cellSize = dtmLayer.cellSize
runningY = dtmLayer.maxY - dtmLayer.cellSize / 2.0
for row in xrange(0, rows):
runningX = dtmLayer.minX + dtmLayer.cellSize / 2.0
for col in xrange(0, cols):
if row == 0 or row == rows-1 or col == 0 or col == cols-1:
continue
v = dtmLayer.getData(0, row, col)
if v == novalue: continue
v11 = dtmLayer.getData(0, row-1, col-1)
v12 = dtmLayer.getData(0, row-1, col)
v13 = dtmLayer.getData(0, row-1, col+1)
v21 = dtmLayer.getData(0, row, col-1)
v23 = dtmLayer.getData(0, row, col+1)
v31 = dtmLayer.getData(0, row+1, col-1)
v32 = dtmLayer.getData(0, row+1, col)
v33 = dtmLayer.getData(0, row+1, col+1)
NEIGHBOUR OPERATIONS: EXTRACT PITS
If the cell is a pit, add it directly to the shapefile:
if v<v11 and v<v12 and v<v13 and v<v21 and v<v23 
and v<v31 and v<v32 and v<v33:
pitPoint = createPoint2D(runningX, runningY)
shape.append(value=v, GEOMETRY=pitPoint)
runningX += cellSize
runningY -= cellSize
shape.commit()
currentView().addLayer(shape)
And never forget to add some style:
pointsLegend = shape.getLegend()
pointSymbol = simplePointSymbol()
pointSymbol.setSize(6);
pointSymbol.setColor(Color.RED);
pointSymbol.setStyle(0);
pointsLegend.setDefaultSymbol(pointSymbol)
shape.setLegend(pointsLegend)
NEIGHBOUR OPERATIONS: EXTRACT PITS
The result should look like:
<license>
This work is released under Creative Commons Attribution Share Alike (CC-BY-SA).
</license>
<sources>
Much of the knowledge needed to create this training material has been produced
by the sparkling knights of the
<a href="http:www.osgeo.org">Osgeo</a>,
<a href="http://tsusiatsoftware.net/">JTS</a>,
<a href="http://www.jgrasstools.org">JGrasstools</a> and
<a href="http:www.gvsig.org">gvSIG</a> communities.
Their websites are filled up with learning material that can be use to grow
knowledge beyond the boundaries of this set of tutorials.
Another essential source has been the Wikipedia project.
</sources>
<acknowledgments>
Particular thanks go to those friends that directly or indirectly helped out in
the creation and review of this series of handbooks.
Thanks to Antonio Falciano for proofreading the course and Oscar Martinez for the
documentation about gvSIG scripting.
</acknowledgments>
<footer>
This tutorial is brought to you by <a href="http:www.hydrologis.com">HydroloGIS</a>.
<footer>

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Data import-cheatsheet
Data import-cheatsheetData import-cheatsheet
Data import-cheatsheet
 
Functor Laws
Functor LawsFunctor Laws
Functor Laws
 
Abstracting over Execution with Higher Kinded Types
Abstracting over Execution with Higher Kinded TypesAbstracting over Execution with Higher Kinded Types
Abstracting over Execution with Higher Kinded Types
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processing
 
Stata Programming Cheat Sheet
Stata Programming Cheat SheetStata Programming Cheat Sheet
Stata Programming Cheat Sheet
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
 
5. R basics
5. R basics5. R basics
5. R basics
 
Generic Functional Programming with Type Classes
Generic Functional Programming with Type ClassesGeneric Functional Programming with Type Classes
Generic Functional Programming with Type Classes
 
Stata cheat sheet analysis
Stata cheat sheet analysisStata cheat sheet analysis
Stata cheat sheet analysis
 
10. Getting Spatial
10. Getting Spatial10. Getting Spatial
10. Getting Spatial
 
Vb.net programs
Vb.net programsVb.net programs
Vb.net programs
 
A Survey Of R Graphics
A Survey Of R GraphicsA Survey Of R Graphics
A Survey Of R Graphics
 
ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions
 
Hive function-cheat-sheet
Hive function-cheat-sheetHive function-cheat-sheet
Hive function-cheat-sheet
 
The Algorithms of CSS @ CSSConf EU 2018
The Algorithms of CSS @ CSSConf EU 2018The Algorithms of CSS @ CSSConf EU 2018
The Algorithms of CSS @ CSSConf EU 2018
 
R Programming: Numeric Functions In R
R Programming: Numeric Functions In RR Programming: Numeric Functions In R
R Programming: Numeric Functions In R
 
Py lecture5 python plots
Py lecture5 python plotsPy lecture5 python plots
Py lecture5 python plots
 
Bridging the Design to Development Gap with CSS Algorithms (Algorithms of CSS...
Bridging the Design to Development Gap with CSS Algorithms (Algorithms of CSS...Bridging the Design to Development Gap with CSS Algorithms (Algorithms of CSS...
Bridging the Design to Development Gap with CSS Algorithms (Algorithms of CSS...
 
Pumps, Compressors and Turbine Fault Frequency Analysis
Pumps, Compressors and Turbine Fault Frequency AnalysisPumps, Compressors and Turbine Fault Frequency Analysis
Pumps, Compressors and Turbine Fault Frequency Analysis
 
The Ring programming language version 1.10 book - Part 127 of 212
The Ring programming language version 1.10 book - Part 127 of 212The Ring programming language version 1.10 book - Part 127 of 212
The Ring programming language version 1.10 book - Part 127 of 212
 

Destacado

CAP Business Plan
CAP Business Plan CAP Business Plan
CAP Business Plan
Phan Anh
 

Destacado (10)

Actividad 2
Actividad 2Actividad 2
Actividad 2
 
Nancy Adilene Gonzalez Sifuentes
Nancy Adilene Gonzalez Sifuentes Nancy Adilene Gonzalez Sifuentes
Nancy Adilene Gonzalez Sifuentes
 
Encuesta a un negocio mercadotecnia electrónica
Encuesta a un negocio mercadotecnia electrónica Encuesta a un negocio mercadotecnia electrónica
Encuesta a un negocio mercadotecnia electrónica
 
แผนที่บ้าน
แผนที่บ้านแผนที่บ้าน
แผนที่บ้าน
 
Presentation1
Presentation1Presentation1
Presentation1
 
CAP Business Plan
CAP Business Plan CAP Business Plan
CAP Business Plan
 
iOpera artigo o que é big data como surgiu o big data para que serve o big data
iOpera artigo o que é big data como surgiu o big data para que serve o big dataiOpera artigo o que é big data como surgiu o big data para que serve o big data
iOpera artigo o que é big data como surgiu o big data para que serve o big data
 
CPA ONE 2016 - Big data: big decisions or big fallacy
CPA ONE 2016 - Big data: big decisions or big fallacyCPA ONE 2016 - Big data: big decisions or big fallacy
CPA ONE 2016 - Big data: big decisions or big fallacy
 
Income tax ordinance (updated 01.07.15) open
Income tax ordinance (updated 01.07.15) openIncome tax ordinance (updated 01.07.15) open
Income tax ordinance (updated 01.07.15) open
 
TDC2016SP - Xamarin.Forms: Uma experiência real de um app iOS e Android com 9...
TDC2016SP - Xamarin.Forms: Uma experiência real de um app iOS e Android com 9...TDC2016SP - Xamarin.Forms: Uma experiência real de um app iOS e Android com 9...
TDC2016SP - Xamarin.Forms: Uma experiência real de um app iOS e Android com 9...
 

Similar a PART 5: RASTER DATA

Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
Kevin Hoyt
 

Similar a PART 5: RASTER DATA (20)

05 Geographic scripting in uDig - halfway between user and developer
05 Geographic scripting in uDig - halfway between user and developer05 Geographic scripting in uDig - halfway between user and developer
05 Geographic scripting in uDig - halfway between user and developer
 
The Ring programming language version 1.7 book - Part 40 of 196
The Ring programming language version 1.7 book - Part 40 of 196The Ring programming language version 1.7 book - Part 40 of 196
The Ring programming language version 1.7 book - Part 40 of 196
 
The Ring programming language version 1.9 book - Part 45 of 210
The Ring programming language version 1.9 book - Part 45 of 210The Ring programming language version 1.9 book - Part 45 of 210
The Ring programming language version 1.9 book - Part 45 of 210
 
Advanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part IIAdvanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part II
 
The Ring programming language version 1.8 book - Part 42 of 202
The Ring programming language version 1.8 book - Part 42 of 202The Ring programming language version 1.8 book - Part 42 of 202
The Ring programming language version 1.8 book - Part 42 of 202
 
Write a Matlab code (a computerized program) for calculating plane st.docx
 Write a Matlab code (a computerized program) for calculating plane st.docx Write a Matlab code (a computerized program) for calculating plane st.docx
Write a Matlab code (a computerized program) for calculating plane st.docx
 
bobok
bobokbobok
bobok
 
A quick introduction to R
A quick introduction to RA quick introduction to R
A quick introduction to R
 
maXbox starter67 machine learning V
maXbox starter67 machine learning VmaXbox starter67 machine learning V
maXbox starter67 machine learning V
 
Data transformation-cheatsheet
Data transformation-cheatsheetData transformation-cheatsheet
Data transformation-cheatsheet
 
CLUSTERGRAM
CLUSTERGRAMCLUSTERGRAM
CLUSTERGRAM
 
Computer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bComputer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1b
 
The Ring programming language version 1.3 book - Part 27 of 88
The Ring programming language version 1.3 book - Part 27 of 88The Ring programming language version 1.3 book - Part 27 of 88
The Ring programming language version 1.3 book - Part 27 of 88
 
The Ring programming language version 1.2 book - Part 26 of 84
The Ring programming language version 1.2 book - Part 26 of 84The Ring programming language version 1.2 book - Part 26 of 84
The Ring programming language version 1.2 book - Part 26 of 84
 
The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 44 of 184The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 44 of 184
 
The Ring programming language version 1.5.3 book - Part 54 of 184
The Ring programming language version 1.5.3 book - Part 54 of 184The Ring programming language version 1.5.3 book - Part 54 of 184
The Ring programming language version 1.5.3 book - Part 54 of 184
 
Practical data science_public
Practical data science_publicPractical data science_public
Practical data science_public
 
Derive hypsometric curves in GRASS GIS
Derive hypsometric curves in GRASS GISDerive hypsometric curves in GRASS GIS
Derive hypsometric curves in GRASS GIS
 
Opensource gis development - part 4
Opensource gis development - part 4Opensource gis development - part 4
Opensource gis development - part 4
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
 

Más de Andrea Antonello

Más de Andrea Antonello (20)

Smash & Geopaparazzi - State of the art 2021
Smash & Geopaparazzi - State of the art 2021Smash & Geopaparazzi - State of the art 2021
Smash & Geopaparazzi - State of the art 2021
 
GEOPAPARAZZI: STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
GEOPAPARAZZI: STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATIONGEOPAPARAZZI: STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
GEOPAPARAZZI: STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
 
GEOPAPARAZZI STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
GEOPAPARAZZI STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATIONGEOPAPARAZZI STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
GEOPAPARAZZI STATE OF THE ART OF THE DIGITAL FIELD MAPPING APPLICATION
 
Geopaparazzi Survey Server workshop
Geopaparazzi Survey Server workshopGeopaparazzi Survey Server workshop
Geopaparazzi Survey Server workshop
 
Geopaparazzi Survey Server Installation
Geopaparazzi Survey Server InstallationGeopaparazzi Survey Server Installation
Geopaparazzi Survey Server Installation
 
Modelling natural hazards in gvSIG with the HortonMachine plugins
Modelling natural hazards in gvSIG with the HortonMachine pluginsModelling natural hazards in gvSIG with the HortonMachine plugins
Modelling natural hazards in gvSIG with the HortonMachine plugins
 
GEOPAPARAZZI: STATE OF THE ART
GEOPAPARAZZI: STATE OF THE ARTGEOPAPARAZZI: STATE OF THE ART
GEOPAPARAZZI: STATE OF THE ART
 
Geopaparazzi - NEVER OUT OF DATA IN THE FIELD
Geopaparazzi - NEVER OUT OF DATA IN THE FIELDGeopaparazzi - NEVER OUT OF DATA IN THE FIELD
Geopaparazzi - NEVER OUT OF DATA IN THE FIELD
 
The HortonMachine, for data analysis to help scientists... and not only
The HortonMachine, for data analysis to help scientists... and not onlyThe HortonMachine, for data analysis to help scientists... and not only
The HortonMachine, for data analysis to help scientists... and not only
 
Geopaparazzi & gvSIG Mobile - state of the art
Geopaparazzi & gvSIG Mobile - state of the artGeopaparazzi & gvSIG Mobile - state of the art
Geopaparazzi & gvSIG Mobile - state of the art
 
Foss4g2016 Geopaparazzi Workshop
Foss4g2016 Geopaparazzi WorkshopFoss4g2016 Geopaparazzi Workshop
Foss4g2016 Geopaparazzi Workshop
 
New tools for LiDAR, forestry, river management and hydro-geomorphology in gvSIG
New tools for LiDAR, forestry, river management and hydro-geomorphology in gvSIGNew tools for LiDAR, forestry, river management and hydro-geomorphology in gvSIG
New tools for LiDAR, forestry, river management and hydro-geomorphology in gvSIG
 
Digital field mapping with Geopaparazzi and gvSIG
Digital field mapping with Geopaparazzi and gvSIGDigital field mapping with Geopaparazzi and gvSIG
Digital field mapping with Geopaparazzi and gvSIG
 
Geopaparazzi, history of a digital mapping kid
Geopaparazzi, history of a digital mapping kidGeopaparazzi, history of a digital mapping kid
Geopaparazzi, history of a digital mapping kid
 
Geopaparazzi, state of the art
Geopaparazzi, state of the artGeopaparazzi, state of the art
Geopaparazzi, state of the art
 
Geographic scripting in uDig
Geographic scripting in uDigGeographic scripting in uDig
Geographic scripting in uDig
 
LESTO - a GIS toolbox for LiDAR empowered sciences
LESTO - a GIS toolbox for LiDAR empowered sciencesLESTO - a GIS toolbox for LiDAR empowered sciences
LESTO - a GIS toolbox for LiDAR empowered sciences
 
04 Geographic scripting in uDig - halfway between user and developer
04 Geographic scripting in uDig - halfway between user and developer04 Geographic scripting in uDig - halfway between user and developer
04 Geographic scripting in uDig - halfway between user and developer
 
02 Geographic scripting in uDig - halfway between user and developer
02 Geographic scripting in uDig - halfway between user and developer02 Geographic scripting in uDig - halfway between user and developer
02 Geographic scripting in uDig - halfway between user and developer
 
Trackoid Rescue - eine mobile Lösung zur Unterstützung von Rettungsmannschaften
Trackoid Rescue - eine mobile Lösung zur Unterstützung von RettungsmannschaftenTrackoid Rescue - eine mobile Lösung zur Unterstützung von Rettungsmannschaften
Trackoid Rescue - eine mobile Lösung zur Unterstützung von Rettungsmannschaften
 

Último

Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
AldoGarca30
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
Kamal Acharya
 

Último (20)

Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 

PART 5: RASTER DATA

  • 1. GEOGRAPHIC SCRIPTING IN GVSIG HALFWAY BETWEEN USER AND DEVELOPER Geoinformation Research Group, Department of Geography University of Potsdam 21-25 November 2016 Andrea Antonello PART 5: RASTER DATA
  • 2. RASTER DATA Raster data can usually be seen as 2 main types: imagery (ex. ortofoto) and physical data (ex. elevation model). While imagery is something you mostly use as nice background data, with an elevation model there are tons of analyses one can do. In this document we will mostly refer to raster as the latter case. Loading raster data in a view is quite simple: rasters = [ "/home/hydrologis/data/potsdam/dsm_test.asc", "/home/hydrologis/data/potsdam/dtm_test.asc" ] epsg = "EPSG:32632" newview = currentProject().createView("Raster view") newview.setProjection(getCRS(epsg)) newview.showWindow() for raster in rasters: loadRasterFile(raster)
  • 3. GET RASTER METADATA To work with raster data it is necessary to get some metadata first. The most used are: rows and cols, boundaries, resolution, bands dtmLayer = currentView().getLayer("dtm_test") print "Raster information: " print "==============================" print "Columns:", dtmLayer.getWidth() print "Rows:", dtmLayer.getHeight() print "NoData value:", dtmLayer.getNoDataValue().getValue() print "Resolution:", dtmLayer.cellSize print "Bands count: ", dtmLayer.getBandsCount() print "Bounds:" print " north: ", dtmLayer.maxX print " south: ", dtmLayer.minX print " west: ", dtmLayer.minY print " east: ", dtmLayer.maxY # values can be read through the getData(band, row, column) method print "Random value: ", dtmLayer.getData(0, 10, 10)
  • 4. THE SIMPLEST RASTER ANALYSIS We now have all the necessary info to loop through the raster data and calculate max, min, average and valid cells dtmLayer = currentView().getLayer("dtm_small") count = 0 sum = 0 min = 10000000 # initialize to something high max = 0 # initialize to something low cols = int(dtmLayer.getWidth()) rows = int(dtmLayer.getHeight()) novalue = -9999.0 # now loop over rows and columns for row in range(0, rows): if row % 10 == 0: print row, " of ", rows, " are done" for col in range(0, cols): value = dtmLayer.getData(0, row, col) if value != novalue: # active cells are only the valid ones count += 1 sum += value if value > max: max = value if value < min: min = value avg = sum/count print "nnMax elevation: ", max print "Min elevation: ", min print "Average elevation: ", avg print "Valid cells: %i of %i" % (count, cols*rows)
  • 5. PUTTING THE RASTER MIN/MAX IN A SHAPEFILE Let's put together what we learned until now to extract the position of the max and min elevation of the raster and place it in a shapefile. Most of the first part is the same as the simple min/max/avg example seen before. In order to put the points in a shapefile we will need the positions. A simple way to get them, is to start in the center of the first cell of the col/row and move pixel by pixel incrementing the X/Y coordinates: cellSize = dtmLayer.cellSize runningY = dtmLayer.maxY - dtmLayer.cellSize / 2.0 for row in xrange(0, rows): runningX = dtmLayer.minX + dtmLayer.cellSize / 2.0 for col in xrange(0, cols): value = dtmLayer.getData(0, row, col) # max/min calculation here runningX += cellSize runningY -= cellSize
  • 6. PUTTING THE RASTER MIN/MAX IN A SHAPEFILE The whole piece will look like: dtmLayer = currentView().getLayer("dtm_small") count = 0; sum = 0 min = 10000000; minX = 0; minY = 0 max = 0; maxX = 0; maxY = 0 cols = dtmLayer.getWidth() rows = dtmLayer.getHeight() novalue = -9999.0 cellSize = dtmLayer.cellSize runningY = dtmLayer.maxY - dtmLayer.cellSize / 2.0 for row in xrange(0, rows): runningX = dtmLayer.minX + dtmLayer.cellSize / 2.0 for col in xrange(0, cols): value = dtmLayer.getData(0, row, col) if value != novalue: count += 1 sum += value if value > max: max = value maxX = runningX maxY = runningY if value < min: min = value minX = runningX minY = runningY runningX += cellSize runningY -= cellSize
  • 7. PUTTING THE RASTER MIN/MAX IN A SHAPEFILE Now that we have positions and values, we can create the shapefile: schema = createFeatureType() schema.append("name", "STRING", 20) schema.append("value", "DOUBLE", 8) schema.append("x", "DOUBLE", 8) schema.append("y", "DOUBLE", 8) schema.append("GEOMETRY", "GEOMETRY") schema.get("GEOMETRY").setGeometryType(POINT, D2) shape = createShape(schema, prefixname="min_max", CRS="EPSG:3003") and insert the data: shape.edit() minPoint = createPoint2D(minX, minY) shape.append(name='MIN', value=min, x=minX, y=minY, GEOMETRY=minPoint) maxPoint = createPoint2D(maxX, maxY) shape.append(name='MAX', value=max, x=maxX, y=maxY, GEOMETRY=maxPoint) shape.commit() currentView().addLayer(shape)
  • 8. PUTTING THE RASTER MIN/MAX IN A SHAPEFILE and since we are at it, let's add some style: pointsLegend = shape.getLegend() pointSymbol = simplePointSymbol() pointSymbol.setSize(15); pointSymbol.setColor(Color.BLUE); pointSymbol.setStyle(3); pointsLegend.setDefaultSymbol(pointSymbol) shape.setLegend(pointsLegend) which should then produce something like:
  • 9. CREATING A NEW ARC/INFO ASCII GRID The Arc/Info ASCII Grid raster format is quite simple to understand. The file starts with a header: NCOLS 355 # number of columns NROWS 361 # number of rows XLLCORNER 1637140.0 # x coordinate of the lower left corner YLLCORNER 5110830.0 # y coordinate of the lower left corner CELLSIZE 10.0 # size of the cell or resolution NODATA_VALUE -9999 # novalue placeholder and after that, the data - space separated - are inserted row by row. First, prepare the input and output data: # open the new file in write mode newRasterPath = "/home/hydrologis/data/potsdam_data/dtm_small_1400_1600.asc" newRasterFile = open(newRasterPath, "w") # get the start raster dtmLayer = currentView().getLayer("dtm_small") cols = dtmLayer.getWidth() rows = dtmLayer.getHeight() novalue = -9999.0
  • 10. CREATING A NEW ASC RASTER We have all the information to write the header: newRasterFile.write("NCOLS " + str(cols)) newRasterFile.write("nNROWS " + str(rows)) newRasterFile.write("nXLLCORNER " + str(dtmLayer.minX)) newRasterFile.write("nYLLCORNER " + str(dtmLayer.minY)) newRasterFile.write("nCELLSIZE " + str(dtmLayer.cellSize)) newRasterFile.write("nNODATA_VALUE " + str(novalue)) Then loop through all the values and filter away the ones outside our range, i.e. set them to novalue: for row in xrange(0, rows): newRasterFile.write("n") for col in xrange(0, cols): value = dtmLayer.getData(0, row, col) if value != novalue and value > 1400 and value < 1600: newRasterFile.write(str(value) + " ") else: newRasterFile.write(str(novalue) + " ") newRasterFile.close() loadRasterFile(newRasterPath)
  • 11. CREATING A NEW ASC RASTER The result, overlayed in greyscale on the original dtm, should look like:
  • 12. NEIGHBOUR OPERATIONS: EXTRACT PITS A pit is a cell in the raster that is lower in elevation than its surrounding cells. Pits are important in hydrology, since "programmatically speaking", the water doesn't flow out of those pits. Let's start by creating the shapefile that will hold the pit points and put it in editing mode: schema = createFeatureType() schema.append("value", "DOUBLE", 8) schema.append("GEOMETRY", "GEOMETRY") schema.get("GEOMETRY").setGeometryType(POINT, D2) shape = createShape(schema, prefixname="pits", CRS="EPSG:3003") shape.edit() and gather the usual information about the raster: # get necessary info from layer dtmLayer = currentView().getLayer("dtm_small") cols = dtmLayer.getWidth() rows = dtmLayer.getHeight() novalue = -9999.0
  • 13. NEIGHBOUR OPERATIONS: EXTRACT PITS The core part loops through the raster values and looks for cells with higher elevation values around them: cellSize = dtmLayer.cellSize runningY = dtmLayer.maxY - dtmLayer.cellSize / 2.0 for row in xrange(0, rows): runningX = dtmLayer.minX + dtmLayer.cellSize / 2.0 for col in xrange(0, cols): if row == 0 or row == rows-1 or col == 0 or col == cols-1: continue v = dtmLayer.getData(0, row, col) if v == novalue: continue v11 = dtmLayer.getData(0, row-1, col-1) v12 = dtmLayer.getData(0, row-1, col) v13 = dtmLayer.getData(0, row-1, col+1) v21 = dtmLayer.getData(0, row, col-1) v23 = dtmLayer.getData(0, row, col+1) v31 = dtmLayer.getData(0, row+1, col-1) v32 = dtmLayer.getData(0, row+1, col) v33 = dtmLayer.getData(0, row+1, col+1)
  • 14. NEIGHBOUR OPERATIONS: EXTRACT PITS If the cell is a pit, add it directly to the shapefile: if v<v11 and v<v12 and v<v13 and v<v21 and v<v23 and v<v31 and v<v32 and v<v33: pitPoint = createPoint2D(runningX, runningY) shape.append(value=v, GEOMETRY=pitPoint) runningX += cellSize runningY -= cellSize shape.commit() currentView().addLayer(shape) And never forget to add some style: pointsLegend = shape.getLegend() pointSymbol = simplePointSymbol() pointSymbol.setSize(6); pointSymbol.setColor(Color.RED); pointSymbol.setStyle(0); pointsLegend.setDefaultSymbol(pointSymbol) shape.setLegend(pointsLegend)
  • 15. NEIGHBOUR OPERATIONS: EXTRACT PITS The result should look like:
  • 16. <license> This work is released under Creative Commons Attribution Share Alike (CC-BY-SA). </license> <sources> Much of the knowledge needed to create this training material has been produced by the sparkling knights of the <a href="http:www.osgeo.org">Osgeo</a>, <a href="http://tsusiatsoftware.net/">JTS</a>, <a href="http://www.jgrasstools.org">JGrasstools</a> and <a href="http:www.gvsig.org">gvSIG</a> communities. Their websites are filled up with learning material that can be use to grow knowledge beyond the boundaries of this set of tutorials. Another essential source has been the Wikipedia project. </sources> <acknowledgments> Particular thanks go to those friends that directly or indirectly helped out in the creation and review of this series of handbooks. Thanks to Antonio Falciano for proofreading the course and Oscar Martinez for the documentation about gvSIG scripting. </acknowledgments> <footer> This tutorial is brought to you by <a href="http:www.hydrologis.com">HydroloGIS</a>. <footer>