SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Downloaden Sie, um offline zu lesen
Java Open Source GIS
          Development

From the building blocks to extending
    an existing GIS application.
 Geoinformation Research Group, Department of Geography
                  University of Potsdam
                      August 2011




                     Part 4: Raster data
                       Tutor: Andrea Antonello




   ydroloGIS             nvironmental                 ngineering
HydroloGIS S.r.l. - Via Siemens, 19 - 39100 Bolzano   www.hydrologis.com
Working with Raster data
When we talk about raster data in GIS we usually mean digital

elevation/terrain/surface models (DEM/DTM/DSM). DEMs can be used to

extract various attributes useful for hydrologic, geomorphologic analyses.

From the DEM maps like aspect, flowdirections, curvatures, gradient and

extracted network can be calculated.


As seen in part 1, a raster is composed of cells and has a value in every cell.

A DEM is a raster that has in every cell the elevation value in that position.


Handling raster data is on one hand trickier than vector data in GeoTools, the

upside is that raster data are so simple, that there is few we need to learn to

be able to process them.
Reading a raster map

The perhaps simplest format for raster data is the ascii grid. An ascii grid is a

cleartext format that contains:

 • a header with:

    • the information of the position of the raster (lower left corner)

    • the size of the cells

    • the number used as novalue
 • the matrix of the data

The dataset we will use for our tests is the spearfish dataset. Please

download it and unzip it in /home/moovida/giscourse/data.
While creating a raster from scratch is not all that easy in GeoTools, reading

it from a map file, is quite easy. All the hard work is done by the coverage

readers, as in the following case by the ArcGridReader:

        ArcGridReader asciiGridReader = new ArcGridReader(file);
        GridCoverage2D readRaster = asciiGridReader.read(null);
        // make sure to get the actual data
        readRaster = readRaster.view(ViewType.GEOPHYSICS);
        asciiGridReader.dispose();



The same concept applies to the writing of raster maps. Once we have the

GridCoverage2D that we want to write to file, we just need the appropriate

writer class:

        ArcGridWriter asciiGridWriter = new ArcGridWriter(file);
        asciiGridWriter.write(readRaster, null);
        asciiGridWriter.dispose();



This obviously makes it easy to create a tool to transform between formats.
To view the newly written geotiff raster map, we first need to read it again:

        GeoTiffReader geoTiffReader = new GeoTiffReader(file);
        readRaster = geoTiffReader.read(null);
        // readRaster = readRaster.view(ViewType.GEOPHYSICS);
        geoTiffReader.dispose();



and pass it with a default style to the map viewer:

        MapContext map = new MapContext();
        map.setTitle("Grid");
        map.setCoordinateReferenceSystem(readRaster.getCoordinateReferenceSystem());
        StyleFactory sf = CommonFactoryFinder.getStyleFactory(GeoTools.getDefaultHints());
        Style style = SLD.wrapSymbolizers(sf.createRasterSymbolizer());
        map.addLayer(readRaster, style);
        JMapFrame.showMap(map);



You should see something like:
Processing a raster map

Processing a raster map basically means doing something with the values

contained in every cell of the map.

To do so we need to be able to iterate over the cells. But first we need to

have the concept of image space and world space clear. Assuming we are

placed north of the equator, the following holds:

                           cols
                                                grid space

                           0,0        1
                rows


                           2         value
                   easting




                                     northing
                       y




                                 x
                                                    world space
In the grid space

Accessing the raster in the grid/image space is usually easier understood.

Most of the times the origin of a raster map is in row = 0 and col = 0 and has

a well defined width and height. Attributes like these can be easily obtained

from the GridCoverage2D through the JGrasstools API:

        RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(readRaster);
        int rows = regionMap.getRows();
        int cols = regionMap.getCols();



Everything boils down to an iteration over cols and rows to access every cell

through the evaluate method. As an example let's calculate the sum of all

the values and the average elevation of the test DEM:

        double sum = 0;
        double[] values = new double[1];
        for( int c = 0; c < cols; c++ ) {
            for( int r = 0; r < rows; r++ ) {
                readRaster.evaluate(new GridCoordinates2D(c, r), values);
                sum = sum + values[0];
            }
        }
        double avg = sum / (rows * cols);
In the world space

When working in the world space, the only thing that changes, is that when

iterating over the position, the bounds and resolution of the raster has to be

considered. They can be obtained from the RegionMap object already used

for the rows and cols:

        double   west = regionMap.getWest();
        double   east = regionMap.getEast();
        double   south = regionMap.getSouth();
        double   north = regionMap.getNorth();
        double   xres = regionMap.getXres();
        double   yres = regionMap.getYres();



Then, we can move cell by cell through the world coordinates:

       sum = 0;
       values = new double[1];
       for( double easting = west + xres / 2.0; easting < east; easting = easting + xres ) {
           for( double northing = south + yres / 2.0; northing < north; northing = northing + yres ) {
               readRaster.evaluate(new Point2D.Double(easting, northing), values);
               sum = sum + values[0];
           }
       }
       avg = sum / (rows * cols);
Writing a raster map

In the previous examples we calculated some simple statistics. Most of the

time the result of a GIS elaboration will be a new raster map that we also

need to write to a file.

As an exercise, let's bring the spearfish mountains to the sea. This basically

means to:

1. search the minimum value of the map

2. create a new raster into which to put the result
3. subtract the minimum to every value and write the result into the new
   raster

4. write the raster to disk
Find minimum:

        double min = Double.POSITIVE_INFINITY;
        for( int c = 0; c < cols; c++ ) {
            for( int r = 0; r < rows; r++ ) {
                readRaster.evaluate(new GridCoordinates2D(c, r), values);
                min = Math.min(values[0], min);
            }
        }



Create an empty new raster to put the result in:

        WritableRaster newWritableRaster = CoverageUtilities.createDoubleWritableRaster(//
                cols, rows, null, null, null);



Note that the raster has been defined only by rows and cols, it lives in the

image space and has no idea were on the world it will be placed.


Make mountains crumble to the sea:

        for( int c = 0; c < cols; c++ ) {
            for( int r = 0; r < rows; r++ ) {
                readRaster.evaluate(new GridCoordinates2D(c, r), values);
                newWritableRaster.setSample(c, r, 0, values[0] - min);
            }
        }
Give the resulting raster a geographic context:

        CoordinateReferenceSystem crs = readRaster.getCoordinateReferenceSystem();
        GridCoverage2D newRaster = CoverageUtilities.buildCoverage(//
                "raster", newWritableRaster, regionMap, crs);



Check the result by loading the read and processed raster in a viewer and

quering the elevation.
From rows/cols to easting/northing and back

The transformation between the two domanis can be done directly from the

GridGeometry.

       GridGeometry2D gridGeometry = readRaster.getGridGeometry();



Image -> World

       int row = 100;
       int col = 50;
       DirectPosition world = gridGeometry.gridToWorld(new GridCoordinates2D(col, row));
       double[] worldArray = world.getCoordinate();
       Coordinate worldCoord = new Coordinate(worldArray[0], worldArray[1]);



World -> Image

       double easting = 591825.0;
       double northing = 4924635.0;
       GridCoordinates2D grid = gridGeometry.worldToGrid(new DirectPosition2D(easting, northing));
       col = grid.x;
       row = grid.y;
Exercises

 • reclassify the spearfish elevation map to have

    • nv: min - 1200.0

    • 1: 1200.0 - 1500.0

    • 2: 1500.0 - 1800.0

    • 3: 1800.0 - max
 • create a map that contains only the values between 1200.0 and 1400.0

Advanced exercises with mixed raster/vector flavour:

 • create the profile of the raster, based on a horizontal LineString that
   passes through the middle of the map

 • create a raster map that has the spearfish elevation values only inside a

   rectangle that is given by the original raster bounding box shrinked by a

   quarter on each side
This work is released under Creative Commons Attribution Share
Alike (CC-BY-SA)

Much of the knowledge needed to create this training material has
been produced by the sparkling knights of the GeoTools, JTS and
uDig community. Another essential source has been the Wikipedia
community effort.

Particular thanks go to those friends that directly or indirectly helped
out in the creation and review of this developer's handbook: Jody
Garnett from the uDig/GeoTools community and the TANTO team.

This tutorial was written with the support of the Geoinformation
Research Group of the University of Potsdam and HydroloGIS.

Weitere ähnliche Inhalte

Was ist angesagt?

Rendering of Complex 3D Treemaps (GRAPP 2013)
Rendering of Complex 3D Treemaps (GRAPP 2013)Rendering of Complex 3D Treemaps (GRAPP 2013)
Rendering of Complex 3D Treemaps (GRAPP 2013)
Matthias Trapp
 
Interactive Rendering and Stylization of Transportation Networks Using Distan...
Interactive Rendering and Stylization of Transportation Networks Using Distan...Interactive Rendering and Stylization of Transportation Networks Using Distan...
Interactive Rendering and Stylization of Transportation Networks Using Distan...
Matthias Trapp
 

Was ist angesagt? (19)

Geometry Batching Using Texture-Arrays
Geometry Batching Using Texture-ArraysGeometry Batching Using Texture-Arrays
Geometry Batching Using Texture-Arrays
 
STATE SPACE GENERATION FRAMEWORK BASED ON BINARY DECISION DIAGRAM FOR DISTRIB...
STATE SPACE GENERATION FRAMEWORK BASED ON BINARY DECISION DIAGRAM FOR DISTRIB...STATE SPACE GENERATION FRAMEWORK BASED ON BINARY DECISION DIAGRAM FOR DISTRIB...
STATE SPACE GENERATION FRAMEWORK BASED ON BINARY DECISION DIAGRAM FOR DISTRIB...
 
Regression kriging
Regression krigingRegression kriging
Regression kriging
 
CS 354 Bezier Curves
CS 354 Bezier Curves CS 354 Bezier Curves
CS 354 Bezier Curves
 
Resource estimation using Surpac software in mining
Resource estimation using Surpac software in mining Resource estimation using Surpac software in mining
Resource estimation using Surpac software in mining
 
CS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and CullingCS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and Culling
 
Linear models
Linear modelsLinear models
Linear models
 
DASH: A C++ PGAS Library for Distributed Data Structures and Parallel Algorit...
DASH: A C++ PGAS Library for Distributed Data Structures and Parallel Algorit...DASH: A C++ PGAS Library for Distributed Data Structures and Parallel Algorit...
DASH: A C++ PGAS Library for Distributed Data Structures and Parallel Algorit...
 
Texture mapping in_opengl
Texture mapping in_openglTexture mapping in_opengl
Texture mapping in_opengl
 
Twopi.1
Twopi.1Twopi.1
Twopi.1
 
Cubist
CubistCubist
Cubist
 
1422798749.2779lecture 5
1422798749.2779lecture 51422798749.2779lecture 5
1422798749.2779lecture 5
 
Raster package jacob
Raster package jacobRaster package jacob
Raster package jacob
 
07object3d
07object3d07object3d
07object3d
 
Rendering of Complex 3D Treemaps (GRAPP 2013)
Rendering of Complex 3D Treemaps (GRAPP 2013)Rendering of Complex 3D Treemaps (GRAPP 2013)
Rendering of Complex 3D Treemaps (GRAPP 2013)
 
Interactive Rendering and Stylization of Transportation Networks Using Distan...
Interactive Rendering and Stylization of Transportation Networks Using Distan...Interactive Rendering and Stylization of Transportation Networks Using Distan...
Interactive Rendering and Stylization of Transportation Networks Using Distan...
 
[Paper] GIRAFFE: Representing Scenes as Compositional Generative Neural Featu...
[Paper] GIRAFFE: Representing Scenes as Compositional Generative Neural Featu...[Paper] GIRAFFE: Representing Scenes as Compositional Generative Neural Featu...
[Paper] GIRAFFE: Representing Scenes as Compositional Generative Neural Featu...
 
Vectors data frames
Vectors data framesVectors data frames
Vectors data frames
 
Support Vector Machines (SVM)
Support Vector Machines (SVM)Support Vector Machines (SVM)
Support Vector Machines (SVM)
 

Ähnlich wie Opensource gis development - part 4

Stockage, manipulation et analyse de données matricielles avec PostGIS Raster
Stockage, manipulation et analyse de données matricielles avec PostGIS RasterStockage, manipulation et analyse de données matricielles avec PostGIS Raster
Stockage, manipulation et analyse de données matricielles avec PostGIS Raster
ACSG Section Montréal
 
Math426_Project3-1
Math426_Project3-1Math426_Project3-1
Math426_Project3-1
Yijun Zhou
 
Remote Sensing: Georeferencing
Remote Sensing: GeoreferencingRemote Sensing: Georeferencing
Remote Sensing: Georeferencing
Kamlesh Kumar
 

Ähnlich wie Opensource gis development - part 4 (20)

Gdistance vignette
Gdistance vignetteGdistance vignette
Gdistance vignette
 
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
 
Stockage, manipulation et analyse de données matricielles avec PostGIS Raster
Stockage, manipulation et analyse de données matricielles avec PostGIS RasterStockage, manipulation et analyse de données matricielles avec PostGIS Raster
Stockage, manipulation et analyse de données matricielles avec PostGIS Raster
 
Maps
MapsMaps
Maps
 
Tall-and-skinny Matrix Computations in MapReduce (ICME colloquium)
Tall-and-skinny Matrix Computations in MapReduce (ICME colloquium)Tall-and-skinny Matrix Computations in MapReduce (ICME colloquium)
Tall-and-skinny Matrix Computations in MapReduce (ICME colloquium)
 
2017 RM-URISA Track: Spatial SQL - The Best Kept Secret in the Geospatial World
2017 RM-URISA Track:  Spatial SQL - The Best Kept Secret in the Geospatial World2017 RM-URISA Track:  Spatial SQL - The Best Kept Secret in the Geospatial World
2017 RM-URISA Track: Spatial SQL - The Best Kept Secret in the Geospatial World
 
Scattered gis handbook
Scattered gis handbookScattered gis handbook
Scattered gis handbook
 
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeksBeginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
 
ClusterAnalysis
ClusterAnalysisClusterAnalysis
ClusterAnalysis
 
Transformations and actions a visual guide training
Transformations and actions a visual guide trainingTransformations and actions a visual guide training
Transformations and actions a visual guide training
 
Math426_Project3-1
Math426_Project3-1Math426_Project3-1
Math426_Project3-1
 
Data Processing Using THEOS Satellite Imagery for Disaster Monitoring (Case S...
Data Processing Using THEOS Satellite Imagery for Disaster Monitoring (Case S...Data Processing Using THEOS Satellite Imagery for Disaster Monitoring (Case S...
Data Processing Using THEOS Satellite Imagery for Disaster Monitoring (Case S...
 
GIS data structure
GIS data structureGIS data structure
GIS data structure
 
Computer Graphics Unit 1
Computer Graphics Unit 1Computer Graphics Unit 1
Computer Graphics Unit 1
 
R Spatial Analysis using SP
R Spatial Analysis using SPR Spatial Analysis using SP
R Spatial Analysis using SP
 
Intro to threp
Intro to threpIntro to threp
Intro to threp
 
Remote Sensing: Georeferencing
Remote Sensing: GeoreferencingRemote Sensing: Georeferencing
Remote Sensing: Georeferencing
 
The Day You Finally Use Algebra: A 3D Math Primer
The Day You Finally Use Algebra: A 3D Math PrimerThe Day You Finally Use Algebra: A 3D Math Primer
The Day You Finally Use Algebra: A 3D Math Primer
 
Feature Extraction Based Estimation of Rain Fall By Cross Correlating Cloud R...
Feature Extraction Based Estimation of Rain Fall By Cross Correlating Cloud R...Feature Extraction Based Estimation of Rain Fall By Cross Correlating Cloud R...
Feature Extraction Based Estimation of Rain Fall By Cross Correlating Cloud R...
 
Feature Extraction Based Estimation of Rain Fall By Cross Correlating Cloud R...
Feature Extraction Based Estimation of Rain Fall By Cross Correlating Cloud R...Feature Extraction Based Estimation of Rain Fall By Cross Correlating Cloud R...
Feature Extraction Based Estimation of Rain Fall By Cross Correlating Cloud R...
 

Mehr von Andrea Antonello

Mehr von 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
 
PART 6: FROM GEO INTO YOUR REPORT
PART 6: FROM GEO INTO YOUR REPORTPART 6: FROM GEO INTO YOUR REPORT
PART 6: FROM GEO INTO YOUR REPORT
 
PART 5: RASTER DATA
PART 5: RASTER DATAPART 5: RASTER DATA
PART 5: RASTER DATA
 
PART 4: GEOGRAPHIC SCRIPTING
PART 4: GEOGRAPHIC SCRIPTINGPART 4: GEOGRAPHIC SCRIPTING
PART 4: GEOGRAPHIC SCRIPTING
 
PART 3: THE SCRIPTING COMPOSER AND PYTHON
PART 3: THE SCRIPTING COMPOSER AND PYTHONPART 3: THE SCRIPTING COMPOSER AND PYTHON
PART 3: THE SCRIPTING COMPOSER AND PYTHON
 
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
 

Kürzlich hochgeladen

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Kürzlich hochgeladen (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 

Opensource gis development - part 4

  • 1. Java Open Source GIS Development From the building blocks to extending an existing GIS application. Geoinformation Research Group, Department of Geography University of Potsdam August 2011 Part 4: Raster data Tutor: Andrea Antonello ydroloGIS nvironmental ngineering HydroloGIS S.r.l. - Via Siemens, 19 - 39100 Bolzano www.hydrologis.com
  • 2. Working with Raster data When we talk about raster data in GIS we usually mean digital elevation/terrain/surface models (DEM/DTM/DSM). DEMs can be used to extract various attributes useful for hydrologic, geomorphologic analyses. From the DEM maps like aspect, flowdirections, curvatures, gradient and extracted network can be calculated. As seen in part 1, a raster is composed of cells and has a value in every cell. A DEM is a raster that has in every cell the elevation value in that position. Handling raster data is on one hand trickier than vector data in GeoTools, the upside is that raster data are so simple, that there is few we need to learn to be able to process them.
  • 3. Reading a raster map The perhaps simplest format for raster data is the ascii grid. An ascii grid is a cleartext format that contains: • a header with: • the information of the position of the raster (lower left corner) • the size of the cells • the number used as novalue • the matrix of the data The dataset we will use for our tests is the spearfish dataset. Please download it and unzip it in /home/moovida/giscourse/data.
  • 4. While creating a raster from scratch is not all that easy in GeoTools, reading it from a map file, is quite easy. All the hard work is done by the coverage readers, as in the following case by the ArcGridReader: ArcGridReader asciiGridReader = new ArcGridReader(file); GridCoverage2D readRaster = asciiGridReader.read(null); // make sure to get the actual data readRaster = readRaster.view(ViewType.GEOPHYSICS); asciiGridReader.dispose(); The same concept applies to the writing of raster maps. Once we have the GridCoverage2D that we want to write to file, we just need the appropriate writer class: ArcGridWriter asciiGridWriter = new ArcGridWriter(file); asciiGridWriter.write(readRaster, null); asciiGridWriter.dispose(); This obviously makes it easy to create a tool to transform between formats.
  • 5. To view the newly written geotiff raster map, we first need to read it again: GeoTiffReader geoTiffReader = new GeoTiffReader(file); readRaster = geoTiffReader.read(null); // readRaster = readRaster.view(ViewType.GEOPHYSICS); geoTiffReader.dispose(); and pass it with a default style to the map viewer: MapContext map = new MapContext(); map.setTitle("Grid"); map.setCoordinateReferenceSystem(readRaster.getCoordinateReferenceSystem()); StyleFactory sf = CommonFactoryFinder.getStyleFactory(GeoTools.getDefaultHints()); Style style = SLD.wrapSymbolizers(sf.createRasterSymbolizer()); map.addLayer(readRaster, style); JMapFrame.showMap(map); You should see something like:
  • 6. Processing a raster map Processing a raster map basically means doing something with the values contained in every cell of the map. To do so we need to be able to iterate over the cells. But first we need to have the concept of image space and world space clear. Assuming we are placed north of the equator, the following holds: cols grid space 0,0 1 rows 2 value easting northing y x world space
  • 7. In the grid space Accessing the raster in the grid/image space is usually easier understood. Most of the times the origin of a raster map is in row = 0 and col = 0 and has a well defined width and height. Attributes like these can be easily obtained from the GridCoverage2D through the JGrasstools API: RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(readRaster); int rows = regionMap.getRows(); int cols = regionMap.getCols(); Everything boils down to an iteration over cols and rows to access every cell through the evaluate method. As an example let's calculate the sum of all the values and the average elevation of the test DEM: double sum = 0; double[] values = new double[1]; for( int c = 0; c < cols; c++ ) { for( int r = 0; r < rows; r++ ) { readRaster.evaluate(new GridCoordinates2D(c, r), values); sum = sum + values[0]; } } double avg = sum / (rows * cols);
  • 8. In the world space When working in the world space, the only thing that changes, is that when iterating over the position, the bounds and resolution of the raster has to be considered. They can be obtained from the RegionMap object already used for the rows and cols: double west = regionMap.getWest(); double east = regionMap.getEast(); double south = regionMap.getSouth(); double north = regionMap.getNorth(); double xres = regionMap.getXres(); double yres = regionMap.getYres(); Then, we can move cell by cell through the world coordinates: sum = 0; values = new double[1]; for( double easting = west + xres / 2.0; easting < east; easting = easting + xres ) { for( double northing = south + yres / 2.0; northing < north; northing = northing + yres ) { readRaster.evaluate(new Point2D.Double(easting, northing), values); sum = sum + values[0]; } } avg = sum / (rows * cols);
  • 9. Writing a raster map In the previous examples we calculated some simple statistics. Most of the time the result of a GIS elaboration will be a new raster map that we also need to write to a file. As an exercise, let's bring the spearfish mountains to the sea. This basically means to: 1. search the minimum value of the map 2. create a new raster into which to put the result 3. subtract the minimum to every value and write the result into the new raster 4. write the raster to disk
  • 10. Find minimum: double min = Double.POSITIVE_INFINITY; for( int c = 0; c < cols; c++ ) { for( int r = 0; r < rows; r++ ) { readRaster.evaluate(new GridCoordinates2D(c, r), values); min = Math.min(values[0], min); } } Create an empty new raster to put the result in: WritableRaster newWritableRaster = CoverageUtilities.createDoubleWritableRaster(// cols, rows, null, null, null); Note that the raster has been defined only by rows and cols, it lives in the image space and has no idea were on the world it will be placed. Make mountains crumble to the sea: for( int c = 0; c < cols; c++ ) { for( int r = 0; r < rows; r++ ) { readRaster.evaluate(new GridCoordinates2D(c, r), values); newWritableRaster.setSample(c, r, 0, values[0] - min); } }
  • 11. Give the resulting raster a geographic context: CoordinateReferenceSystem crs = readRaster.getCoordinateReferenceSystem(); GridCoverage2D newRaster = CoverageUtilities.buildCoverage(// "raster", newWritableRaster, regionMap, crs); Check the result by loading the read and processed raster in a viewer and quering the elevation.
  • 12. From rows/cols to easting/northing and back The transformation between the two domanis can be done directly from the GridGeometry. GridGeometry2D gridGeometry = readRaster.getGridGeometry(); Image -> World int row = 100; int col = 50; DirectPosition world = gridGeometry.gridToWorld(new GridCoordinates2D(col, row)); double[] worldArray = world.getCoordinate(); Coordinate worldCoord = new Coordinate(worldArray[0], worldArray[1]); World -> Image double easting = 591825.0; double northing = 4924635.0; GridCoordinates2D grid = gridGeometry.worldToGrid(new DirectPosition2D(easting, northing)); col = grid.x; row = grid.y;
  • 13. Exercises • reclassify the spearfish elevation map to have • nv: min - 1200.0 • 1: 1200.0 - 1500.0 • 2: 1500.0 - 1800.0 • 3: 1800.0 - max • create a map that contains only the values between 1200.0 and 1400.0 Advanced exercises with mixed raster/vector flavour: • create the profile of the raster, based on a horizontal LineString that passes through the middle of the map • create a raster map that has the spearfish elevation values only inside a rectangle that is given by the original raster bounding box shrinked by a quarter on each side
  • 14. This work is released under Creative Commons Attribution Share Alike (CC-BY-SA) Much of the knowledge needed to create this training material has been produced by the sparkling knights of the GeoTools, JTS and uDig community. Another essential source has been the Wikipedia community effort. Particular thanks go to those friends that directly or indirectly helped out in the creation and review of this developer's handbook: Jody Garnett from the uDig/GeoTools community and the TANTO team. This tutorial was written with the support of the Geoinformation Research Group of the University of Potsdam and HydroloGIS.