Skip to main content

Chapter 0: One command, one file

Chapter 0: One command, one file

TipAt a glance
  • In this series: An introduction for beginners, with the commands of GDAL in short examples. The longer chapters begin with Chapter 1. Come back here when you need a command
  • You will build: A map of Lake Toba in five short commands, the same map in one line, and then a collection of 166 everyday cases, most of them one line each
  • You need: A conda installation such as Miniforge. After the installation, no internet connection: all data is in the folder of the chapter
  • Time to run: The commands took less than six minutes when tested, plus the time to install GDAL. The introduction, sections 1 to 9, takes half a minute of this
  • Level: Beginner: no GDAL needed before this

The later chapters have long command lines. A long line consists of several small commands, and each of them is easy.

This chapter explains the small commands. It starts with one command that reads one file and changes nothing. Then a command makes one file from another, then one file from two. At the end, the same commands are combined in one line, and you can read it.

After this introduction comes a collection: cases from daily work with reliefs, satellite images, climate data and tables. Each has a short question, a line, and a short explanation. You do not have to read them in order.

The place is Lake Toba in Sumatra, the crater of a huge old volcano. In the lake lies the island Samosir, which is called the largest island within an island in the world (ledger L89).

NoteLearning objectives

By the end of this chapter you will be able to:

  • read what a file contains;
  • read any GDAL command as four parts: program, input, output, options;
  • make a new file from one file, and from two;
  • recognise the most common reasons why a result looks wrong;
  • combine two commands in one line, and know why that is useful;
  • write a first query for a table;
  • read a long line by dividing it into its steps;
  • open netCDF and HDF5 files, and calculate with many dates;
  • find the right line for most everyday jobs with rasters and tables.

Before running this chapter, create the environment of section 1. Paste the lines into a terminal one by one, or run them from this notebook. If you know GDAL already, read section 8 and go on to Chapter 1.

1. Get GDAL, and a place to work

GDAL is a library for geospatial data that comes with command-line programs. Install it with the rest of this series’ software, from the folder of the repository:

conda env create -f environment.yml
conda activate gdal-oneliners

In a terminal: make an empty folder, go there, and copy into it the files from sample-data/ch00.

In this notebook: the next cell does that for you. It also adds %%line. A cell that starts with %%line holds command lines, each on its own row, and hands them unchanged to the shell of your operating system. What you see in such a cell is what you would paste into a terminal. The website leaves the %%line row out.

import sys
import time
from pathlib import Path

# The repository root, whether the notebook runs from en/, id/ or the root itself
ROOT = Path.cwd() if (Path.cwd() / "tutorial.yml").exists() else Path.cwd().parent
sys.path.insert(0, str(ROOT / "src"))
import oneline

T0 = time.perf_counter()
WORK = oneline.start("00")          # a folder outside the repository; see src/oneline.py to choose it
print("working folder:", WORK.name, "| files copied there:", sorted(f.name for f in (ROOT / "sample-data/ch00").iterdir()))
working folder: ch00 | files copied there: ['before.tif', 'bow.geojson', 'districts.gpkg', 'east.tif', 'messy.csv', 'minutes.csv', 'ndvi.txt', 'old.dbf', 'old.shp', 'rain.nc', 'samples.csv', 'scan.jpg', 'scene.tif', 'sea.h5', 'sea360.tif', 'toba.txt', 'towns.csv', 'west.tif']
gdal --version
GDAL 3.12.3 "Chicoutimi", released 2026/03/17

Look before moving on. If you see a version, GDAL works. This series was tested with 3.12.3 (ledger L1). If the answer is “not recognized” or “command not found”, the environment is not active: run conda activate gdal-oneliners again.

The program gdal is new, and its makers may still change it (ledger L2). You may know the older ones, such as gdalwarp and ogr2ogr. They all still work, and section 9 compares the two groups.

2. One file, and nothing changes

Geospatial data comes in two forms. A raster is a grid of numbers, such as heights. A vector layer is a table in which each row has a shape, such as a district.

Start by reading the contents of a raster. This command only reads, so it cannot damage the file:

gdal raster info west.tif
Driver: GTiff/GeoTIFF
Files: west.tif
Size is 1260, 1710
Coordinate System is:
GEOGCRS["WGS 84",
    ENSEMBLE["World Geodetic System 1984 ensemble",
        MEMBER["World Geodetic System 1984 (Transit)"],
        MEMBER["World Geodetic System 1984 (G730)"],
        MEMBER["World Geodetic System 1984 (G873)"],
        MEMBER["World Geodetic System 1984 (G1150)"],
        MEMBER["World Geodetic System 1984 (G1674)"],
        MEMBER["World Geodetic System 1984 (G1762)"],
        MEMBER["World Geodetic System 1984 (G2139)"],
        MEMBER["World Geodetic System 1984 (G2296)"],
        ELLIPSOID["WGS 84",6378137,298.257223563,
            LENGTHUNIT["metre",1]],
        ENSEMBLEACCURACY[2.0]],
    PRIMEM["Greenwich",0,
        ANGLEUNIT["degree",0.0174532925199433]],
    CS[ellipsoidal,2],
        AXIS["geodetic latitude (Lat)",north,
            ORDER[1],
            ANGLEUNIT["degree",0.0174532925199433]],
        AXIS["geodetic longitude (Lon)",east,
            ORDER[2],
            ANGLEUNIT["degree",0.0174532925199433]],
    USAGE[
        SCOPE["Horizontal component of 3D system."],
        AREA["World."],
        BBOX[-90,-180,90,180]],
    ID["EPSG",4326]]
Data axis to CRS axis mapping: 2,1
Origin = (98.299999999999997,3.100000000000000)
Pixel Size = (0.000555555555556,-0.000555555555556)
Metadata:
  AREA_OR_POINT=Area
Image Structure Metadata:
  COMPRESSION=DEFLATE
  INTERLEAVE=BAND
  PREDICTOR=2
Corner Coordinates:
Upper Left  (  98.3000000,   3.1000000) ( 98d18' 0.00"E,  3d 6' 0.00"N)
Lower Left  (  98.3000000,   2.1500000) ( 98d18' 0.00"E,  2d 9' 0.00"N)
Upper Right (  99.0000000,   3.1000000) ( 99d 0' 0.00"E,  3d 6' 0.00"N)
Lower Right (  99.0000000,   2.1500000) ( 99d 0' 0.00"E,  2d 9' 0.00"N)
Center      (  98.6500000,   2.6250000) ( 98d39' 0.00"E,  2d37'30.00"N)
Band 1 Block=1260x3 Type=Int16, ColorInterp=Gray

That is a lot of text, and five facts are enough for now:

Look for Here Meaning
Size is 1260, 1710 columns and rows
ID["EPSG",4326] the last one of the long block the coordinates are longitude and latitude, in degrees
Pixel Size 0.000556 the width of a cell in degrees, here about 60 m
Upper Left, Lower Right 98.3 to 99.0 east, 2.15 to 3.1 north where the raster lies
Type=Int16 at the end whole numbers, which can be negative

Now a vector file. --summary keeps the answer short:

gdal vector info districts.gpkg --summary

gdal vector convert districts.gpkg /vsistdout/ --output-format CSV
INFO: Open of `districts.gpkg'
      using driver `GPKG' successful.
1: district (Multi Polygon)
name,code
Asahan,ID1208
Dairi,ID1210
Danau Toba,ID1288
Deli Serdang,ID1212
Humbang Hasundutan,ID1215
Karo,ID1211
Kota Pematang Siantar,ID1273
Labuhan Batu Utara,ID1223
Pakpak Bharat,ID1216
Samosir,ID1217
Serdang Bedagai,ID1218
Simalungun,ID1209
Tapanuli Utara,ID1205
Toba Samosir,ID1206

The file has one layer, district, made of polygons. The second command writes its table to the screen, which GDAL calls /vsistdout/. These are the districts around the lake, and the lake itself is one of them (ledger L66).

One question more. How high is the water at one point of the lake, at 98.6 degrees east and 2.8 north?

gdal raster pixel-info west.tif 98.6 2.8 --position-crs EPSG:4326 --output-format CSV
input_x,input_y,extra_input,column,line,band_1_raw_value,band_1_unscaled_value
98.599999999999994,2.7999999999999998,"",540,540,901,901

The last number is the height of the water: 901 m. Section 5 uses it.

3. One file in, one file out

Nearly every GDAL command has the same four parts:

gdal raster hillshade     west.tif     shade_west.png     --overwrite
program                   input        output             options

hillshade calculates how the land looks when the light comes from the upper left. The ending .png tells GDAL which kind of file you want:

gdal raster hillshade west.tif shade_west.png --overwrite

A grey relief of the western part of Lake Toba, lit from the upper left. The lake is a smooth plain with steep walls around it. The right edge of the picture cuts the lake in two.

Look before moving on. One short command makes a picture of the landscape. The flat part is the lake, and the steep slopes around it are the rim of the crater. The picture ends in the middle of the lake, because the rest is in another file. Section 5 combines the two files.

--overwrite allows GDAL to replace a file that is already there. Without it, the same command works once and refuses the second time. This protects your files, so leave it out when you are not sure.

The other commands of this kind differ in one word. Run them one by one, and look at each result in a program such as QGIS:

gdal raster resize west.tif small.tif --size 315,0 -r average --overwrite

gdal raster clip west.tif corner.tif --bbox 98.4,2.5,98.7,2.8 --overwrite

gdal raster reproject west.tif west_utm.tif --dst-crs EPSG:32647 --overwrite

gdal raster slope west.tif slope.tif --overwrite

gdal raster contour west.tif lines.gpkg --interval 100 --elevation-name height --overwrite
Command What comes out
resize fewer and larger cells. 315 columns, and 0 means “as many rows as it needs”. -r average takes the mean of the old cells
clip a piece. The four numbers are west, south, east and north
reproject the same land in another coordinate system, here UTM zone 47 north, which counts in metres
slope the steepness of each cell, in degrees
contour raster in, vector out: a line every 100 m, with the height in the column height

Vector files work in the same way. The ending of the output chooses the format:

gdal vector convert districts.gpkg districts.geojson --overwrite

gdal vector rasterize lines.gpkg lines.tif --burn 255 --ot Byte --size 1260,1710 --overwrite

gdal raster edit lines.tif --nodata none

gdal raster convert lines.tif lines.png --overwrite

White contour lines on black. They are close together on the steep slopes of the crater, and there are none on the lake.

The second one converts in the other direction, from vector to raster. It draws the contour lines with the number 255, which is white, on a ground of 0, which is black. The third one looks unimportant, and without it you would see nothing. rasterize writes a note into the file that 0 means “no data”. In a PNG file, cells without data are transparent. So the black ground would disappear, and white lines would be left on a white page. edit --nodata none removes the note. It changes the file itself, and not one number in it.

The last one only changes the format. rasterize cannot write a PNG file directly, so it first writes a GeoTIFF (.tif), which every command can read and write.

4. When the result looks wrong

A wrong result usually has one of a few causes. Here is the most common one. Convert the heights into a picture:

gdal raster convert west.tif white.png --overwrite
Warning 6: PNG driver doesn't support data type Int16. Only eight bit (Byte) and sixteen bit (UInt16) bands supported. Defaulting to Byte

A nearly white picture. Only a few grey spots are left in two corners.

The picture is almost white, and GDAL has printed a warning. A grey PNG picture can store numbers up to 255, or up to 65,535 in its larger form. GDAL used the small form, and every height above 255 m became 255, which is white. Almost all of this land is higher.

The numbers have to be scaled to this range first. This takes one command, too. It makes the lowest place black and the highest white:

gdal raster scale west.tif grey.png --ot Byte --overwrite

The same land in grey: dark valleys, a grey lake and pale mountains.

Look before moving on. Read what a command prints. A warning does not stop it, and the file is there, but it may not be what you wanted. If a command prints nothing at all, it found no problem.

5. Two files in, one file out

Reliefs come in tiles, and here the border between two tiles runs through the middle of the lake. mosaic puts them together. The last name is always the output:

gdal raster mosaic west.tif east.tif toba.tif --overwrite

The next command also takes two files: a raster, and a small text file with colours.

gdal raster color-map toba.tif colour.tif --color-map toba.txt --overwrite
print((WORK / "toba.txt").read_text())
# order: 0 500 1300 1800 2500
0 70 105 80
500 112 140 98
900.4 150 163 112
900.5 58 110 148
901.5 58 110 148
901.6 150 163 112
1300 190 178 128
1800 214 196 164
2500 248 244 236

Each row has a height and a colour, as red, green and blue from 0 to 255. Between two rows, GDAL mixes the colours. The first row is a comment for the reader.

Four rows are for the lake. The water lies at 901 m, so the colour is blue between 900.5 and 901.5 m, and green again just below and just above. This gives the lake its colour without a file of the lake.

Now calculate the shade, and then combine both. blend puts the second raster over the first one. With hsv-value, the colour comes from the first file and the brightness from the second:

gdal raster hillshade toba.tif shade.tif --overwrite

gdal raster blend colour.tif shade.tif map.tif --operator hsv-value --overwrite

gdal raster resize map.tif map.png --size 990,0 -r average --overwrite

A coloured relief of Lake Toba. The blue lake surrounds the long, tilted island Samosir. Steep walls stand around the water, and the land falls away to green lowlands in the north-east and south-west.

Look before moving on. This map took five short commands: mosaic, color-map, hillshade, blend, resize. Each of them made a file that you can open and check.

This method has one error. Look closely at the upper middle, north-east of the lake: there are a few tiny blue spots on dry land. This land is 901 m high, too.

A raster and a vector layer can also be used together. Which district has the highest place? zonal-stats collects the cells in each shape, and writes a table:

gdal raster zonal-stats toba.tif /vsistdout/ --zones districts.gpkg --stat max --include-field name --output-format CSV
name,max
Asahan,2185
Dairi,2445
Danau Toba,1094
Deli Serdang,1708
Humbang Hasundutan,2032
Karo,2441
Kota Pematang Siantar,584
Labuhan Batu Utara,1891
Pakpak Bharat,1827
Samosir,2145
Serdang Bedagai,1232
Simalungun,2083
Tapanuli Utara,2044
Toba Samosir,2280

Be careful with such numbers. Some of the districts reach beyond our raster, and then this is only the highest place in the part we have. And the highest place in the lake is said to be 1,094 m, although the water lies at 901 m. The borders of the districts are drawn a little more simply than the real shore, so at some places the polygon of the lake includes a part of the slope.

6. A first query

Most work with vector data starts with choosing rows. filter keeps the rows for which a condition is true:

gdal vector filter districts.gpkg lake.gpkg --where "name='Danau Toba'" --overwrite

The quotes are necessary. The outer ones are double, and mark the whole condition. The inner ones are single, and mark a piece of text. Numbers have no quotes: --where "height>2000".

With sql you can choose and calculate columns. SQL is the language of databases, and it uses English words:

gdal vector sql districts.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select name, round(st_area(geom,1)/1e6) km2 from district order by km2 desc"
name,km2
Simalungun,4405
Asahan,3780
Tapanuli Utara,3713
Labuhan Batu Utara,3577
Deli Serdang,2595
Humbang Hasundutan,2531
Karo,2177
Toba Samosir,2146
Dairi,1993
Serdang Bedagai,1941
Pakpak Bharat,1322
Samosir,1238
Danau Toba,1102
Kota Pematang Siantar,76
Part Meaning
select name, ... km2 show these two columns
st_area(geom,1)/1e6 the area of the shape geom, measured on the curved Earth, in square metres, divided by a million. round removes the decimals
from district from this layer
order by km2 desc the largest first. desc is short for descending

Is it right? An encyclopaedia gives 1,130 km2 for Lake Toba (ledger L89). Our lake has 1,102 km2, which is 2.5 percent less. For a simplified border, that is fine.

7. Two commands, one line

How does the land within 5 km of the lake look? There are three steps. Take the lake, which we have already. Change it to a coordinate system in metres, because 5 km cannot be said in degrees. Then draw a border around it at a distance of 5,000 m:

gdal vector reproject lake.gpkg lake_utm.gpkg --dst-crs EPSG:32647 --overwrite

gdal vector buffer lake_utm.gpkg near.geojson --distance 5000 --overwrite

It works, and it leaves files behind that are not needed again. A pipeline does the same in one line. The steps are separated by exclamation marks, and each step passes its result to the next:

gdal vector pipeline read districts.gpkg ! filter --where "name='Danau Toba'" ! reproject --dst-crs EPSG:32647 ! buffer --distance 5000 ! write near_lake.geojson --overwrite

Compare it with the commands before. The words filter, reproject and buffer are the same, with the same options. Only the file names between them are gone. A pipeline begins with read and ends with write.

Now use the new shape to cut the map:

gdal raster clip map.tif around.png --like near_lake.geojson --add-alpha --overwrite

Lake Toba cut out of the map, with the land up to five kilometres from the shore. The outer border is a chain of round arcs. In the middle of Samosir there is a hole, because the inner part of the island is farther from the water.

Look before moving on. --add-alpha makes everything outside transparent. Samosir has a hole: the middle of the island is more than 5 km from the water. The shape is in metres and the map in degrees. Both files contain their coordinate system, so GDAL converts one into the other.

8. The whole chapter in one line

The map of section 5 needed four commands before the last one made it smaller. Here they are in one line:

gdal pipeline mosaic west.tif east.tif ! color-map --color-map toba.txt ! blend --overlay [ mosaic west.tif east.tif ! hillshade ] --operator hsv-value ! write whole.tif --overwrite

Divide the line at every exclamation mark:

Step Meaning
gdal pipeline mosaic west.tif east.tif put the two tiles together
color-map --color-map toba.txt give every height a colour
blend --overlay [ ... ] --operator hsv-value put a second raster over it
[ mosaic west.tif east.tif ! hillshade ] the second raster. The square brackets contain a small pipeline: the two tiles again, then the shade
write whole.tif --overwrite and store the result

compare compares two rasters cell by cell and reports every difference:

gdal raster compare map.tif whole.tif

It prints nothing, so there is none. The long line and the four short commands made exactly the same map.

Which way is better? Both. Use short commands while you are still testing, and check each file. When everything is right, put the steps into one line, so that you can keep it, send it to someone, or run it again next month with new data.

You can divide every line in this series in the same way. This is the one that draws the first map of Chapter 1. You do not need to understand it today:

gdal pipeline read world.gpkg
  ! sql "select 1 v, geom from land union all select 2, geom from land where admin='Indonesia' union all ..."
  ! rasterize --attribute-name v --init 0 --ot Byte --size "1800,680" --extent "-180,-58,180,78"
  ! edit --nodata none
  ! color-map --color-map antipode.txt
  ! write antipode.png --overwrite

But you know most of it already. It reads a file, selects shapes with SQL, draws them as numbers, gives every number a colour, and writes a picture. Only the SQL part is long.

9. The same with the older names

Most examples on the internet use the older programs, and so do many lines in this series. They do the same work under other names:

Task gdal Older program
look at a raster gdal raster info gdalinfo
look at a vector file gdal vector info ogrinfo
other format, other size gdal raster convert, resize gdal_translate
other coordinate system, cut, join gdal raster reproject, clip, mosaic gdalwarp, gdalbuildvrt
shade, slope, colours gdal raster hillshade, slope, color-map gdaldem hillshade, slope, color-relief
contour lines, polygons from cells gdal raster contour, polygonize gdal_contour, gdal_polygonize.py
cut along a border gdal raster clip --like gdalwarp -cutline border.shp -crop_to_cutline
calculate with rasters gdal raster calc gdal_calc.py
change notes, corners or the coordinate system of a file gdal raster edit gdal_edit.py
cells as a text table, tiles for a web page gdal raster convert --output-format XYZ, gdal raster tile gdal2xyz.py, gdal2tiles.py
one variable of a netCDF or HDF5 file gdal raster convert NETCDF:a.nc:rain gdal_translate NETCDF:a.nc:rain
a piece of a cube gdal mdim convert gdalmdimtranslate
anything with vector files gdal vector convert, filter, sql, reproject, clip ogr2ogr, with -where, -sql, -t_srs, -clipsrc
many vector files into one layer gdal vector concat --mode single ogrmerge.py -single

Try some of them:

gdalwarp -q -overwrite west.tif east.tif old_toba.tif

gdaldem hillshade -q -compute_edges old_toba.tif old_shade.tif

gdaldem color-relief -q old_toba.tif toba.txt old_colour.tif

ogr2ogr -overwrite old_lake.gpkg districts.gpkg -where "name='Danau Toba'"
gdal raster compare shade.tif old_shade.tif

gdal raster compare colour.tif old_colour.tif

Again compare prints nothing, so the results are the same. Two differences are important:

  • ogr2ogr needs the output first and the input second, and so does gdalbuildvrt. The new program always has the input first.
  • The defaults are not always the same. The old hillshade leaves the outermost cells empty, unless -compute_edges is there. The new one fills them.

The collection

The sections of the introduction have numbers, and the collection has letters. Each subject has a letter, and the cases of subject A are A1, A2 and so on.

Here are 166 cases. Each is a small job from daily work, and nearly every one is a single line. The introduction has explained the parts of these commands. The lines use its files, and sometimes a file of an earlier case, so run the introduction first if you want to try them.

Under many lines there is a small picture. It is a preview made by this notebook, with black for the lowest and white for the highest number of a raster. In your own work, open the file in QGIS.

Subject I want to know, or to make
A Information from a raster A1: Where does this raster lie, as a shape? · A2: What are the lowest, the mean and the highest value? · A3: Where is the highest place of each district? · A4: How high are these two towns? · A5: What does a raster look like as numbers? · A6: Print every cell with its position
B Information from a vector file B1: How many rows are there? · B2: Which values does a column have, and how often? · B3: Which three districts are the largest? · B4: How long is the border of each district? · B5: Where is the middle of each district? · B6: Which districts touch the lake?
C A raster in another size or shape C1: Cells of exactly 100 metres · C2: Only the first 500 columns and rows · C3: Cut along a border · C4: Rotate the map until the lake is horizontal · C5: Put a frame around a map · C6: How coarse can a map be?
D A raster with other numbers D1: From metres to feet · D2: Heights above the lake instead of above the sea · D3: Which land lies less than 100 m above the water? · D4: Four classes instead of thousands of heights · D5: Remove very small areas · D6: Smooth a relief · D7: Find the edges · D8: What is the highest place within 1 km? · D9: Remove the lake · D10: Fill a hole from its edges · D11: How far is it to the lake, from anywhere?
E Light, slope and the form of the land E1: Evening light · E2: Light from several sides · E3: Make small hills visible · E4: How steep is it? · E5: In which direction does each slope face? · E6: How rough is it? · E7: Ridges and valleys · E8: Draw the shore · E9: Areas between heights · E10: What can you see from the top of a volcano?
F Satellite images F1: What does the satellite measure at one place? · F2: Natural colours · F3: Make it bright enough · F4: Plants in bright green · F5: Make the dark parts brighter · F6: How green is it? (NDVI) · F7: The same with colours for soil, plants and water · F8: Where is water? · F9: From stored numbers to real ones · F10: Make the empty corner transparent · F11: Sharpen · F12: Two rasters on the same grid · F13: Forest above 1,500 m
G NetCDF: many dates in one file G1: What is in this file? · G2: One variable as a GeoTIFF · G3: The file has no coordinate system · G4: Only March · G5: Only March, and still a netCDF file · G6: January to March by their dates · G7: The whole year at one place · G8: The rain of the whole year · G9: The same, and “no data” stays “no data” · G10: The mean, the driest and the wettest month of each cell · G11: How many months had more than 200 mm? · G12: Add them up · G13: Was March wetter or drier than usual? · G14: On a scale from 0 to 100 · G15: The rain of each district · G16: Back to netCDF
H HDF5: a file without coordinates H1: What is in this file? · H2: Add the coordinates · H3: Degrees Celsius · H4: Degrees Fahrenheit · H5: Why is my map upside down? · H6: Do not turn it
I Pictures and files for other people I1: A table for a spreadsheet · I2: A plain binary file with a header · I3: A small picture for an e-mail · I4: The same file, but smaller · I5: Write a note into a file · I6: A file for the cloud · I7: A map for Google Earth · I8: Tiles for a web page · I9: Only 16 colours · I10: Slope, shade and height as red, green and blue
J Rows and columns J1: Keep some columns · J2: Keep some rows · J3: All names that start with Pa · J4: Sort by a column · J5: Give a column a new name, and add another one
K Points, tables and devices K1: From a table to points · K2: From points to a table · K3: An Excel file · K4: An Esri geodatabase · K5: Points for a GPS device · K6: A file for Google Earth or a phone · K7: A shapefile, if somebody asks for one · K8: Short coordinates for a web page · K9: Pack a file into a zip, and go on using it
L New shapes from old ones L1: A simpler border · L2: A simpler border without gaps · L3: One shape out of many · L4: A box around each shape · L5: The convex hull of all towns · L6: Only the lines · L7: A grid of hexagons · L8: One row for each hexagon · L9: Is every shape valid?
M Two files together M1: Cut a layer with a box · M2: Keep what lies inside another layer · M3: Keep what lies outside · M4: Two layers into one file · M5: Which district is each town in? · M6: How many towns lie in each district? · M7: How far is each town from the lake? · M8: Lay one picture over another, half transparent · M9: Paste a piece into a larger raster
N Many files from one, one from many N1: A file for each value · N2: What is in a folder? · N3: A mosaic in a very small file · N4: A map of your rasters · N5: One band out of three
O From raster to vector, and back O1: Polygons from classes · O2: Points from cells · O3: Cells from shapes, with a number from the table · O4: Where are the towns close together? · O5: The mean height of each district
P Two or three steps in one line P1: Cut, then shade · P2: Smooth, then draw lines · P3: The flat land · P4: The lake without the district file · P5: Is it the same lake? · P6: Colours and size in one go
Q Map projections Q1: Which UTM zone does my place have? · Q2: Where is this place in metres? · Q3: How large is it, really? · Q4: How far is everything from here? · Q5: The world with Indonesia in the middle · Q6: An old datum moves a place by 168 m
R A scan without coordinates R1: Does this picture have coordinates? · R2: I know the corners · R3: Which grid is printed on it? · R4: Is it this one? · R5: I know four points · R6: How good is it? · R7: Reproject it to the grid of the satellite image · R8: Old and new in one picture
S From points to a surface S1: The value of the nearest point · S2: Straight lines between the points · S3: Near points count more · S4: Which one is best? · S5: The mean error
T Two dates T1: How green was it then? · T2: Two dates in one picture · T3: New minus old · T4: Where did the plants disappear? · T5: How many hectares is that? · T6: Without the clouds
U Common problems with files U1: My points are in the wrong ocean · U2: Commas in the numbers · U3: Degrees, minutes and seconds · U4: The layer has no coordinate system · U5: The area of my field is 0 · U6: A part of the shapefile is missing · U7: The names are unreadable · U8: The minimum is -9999 · U9: The map begins at Greenwich
V The same for a whole folder loops for cmd, PowerShell and bash

A: Information from a raster

These lines read information from a raster and do not change it.

A1: Where does this raster lie, as a shape?

Sometimes you want to see only the outline of a file, for example to lay many of them on one map.

gdal raster footprint toba.tif footprint.geojson --overwrite

The result is one polygon around all cells that have a value. QGIS, a web map or Google Earth can show it.

A2: What are the lowest, the mean and the highest value?

zonal-stats collects the cells inside a shape. The outline of the whole raster is a shape, too.

gdal raster zonal-stats toba.tif /vsistdout/ --output-format CSV --zones footprint.geojson --stat min --stat mean --stat max
min,mean,max
30,1014.03544302676,2445

From the lowlands in the north-east to the highest mountain, in metres.

A3: Where is the highest place of each district?

The same command can also report the position of the highest cell.

gdal raster zonal-stats toba.tif /vsistdout/ --output-format CSV --zones districts.gpkg --include-field name --stat max --stat max_center_x --stat max_center_y --strategy raster
name,max,max_center_x,max_center_y
Asahan,2185,99.0797222222222,2.59138888888889
Dairi,2445,98.4236111111111,2.91805555555556
Danau Toba,1094,98.9230555555555,2.6975
Deli Serdang,1708,98.6302777777778,3.09583333333333
Humbang Hasundutan,2032,98.5975,2.19583333333333
Karo,2441,98.4297222222222,2.9175
Kota Pematang Siantar,584,99.0175,2.89361111111111
Labuhan Batu Utara,1891,99.3997222222222,2.17083333333333
Pakpak Bharat,1827,98.3813888888889,2.4675
Samosir,2145,98.7463888888889,2.46194444444444
Serdang Bedagai,1232,98.9436111111111,3.01694444444444
Simalungun,2083,99.0736111111111,2.60638888888889
Tapanuli Utara,2044,99.3947222222222,2.15027777777778
Toba Samosir,2280,99.3613888888889,2.17194444444444

The last two numbers are longitude and latitude. --strategy raster is needed here, because the other way of counting crashes with these two (ledger L72).

A4: How high are these two towns?

The command accepts several places at once. These are Parapat on the shore and Pangururan on Samosir.

gdal raster pixel-info toba.tif 98.9349 2.663 98.6961 2.6081 --position-crs EPSG:4326 --output-format CSV
input_x,input_y,extra_input,column,line,band_1_raw_value,band_1_unscaled_value
98.934899999999999,2.6629999999999998,"",1142.820000000007,786.60000000000036,941,941
98.696100000000001,2.6080999999999999,"",712.98000000001048,885.42000000000007,912,912

One row for each place. The height stands in the column band_1_raw_value.

A5: What does a raster look like as numbers?

Make it tiny first, or the list will be very long.

gdal raster resize toba.tif tiny.tif --size 4,3 -r average --overwrite

Now the twelve cells can be printed:

A6: Print every cell with its position

XYZ is the simplest raster format there is: east, north and value.

gdal raster convert tiny.tif /vsistdout/ --output-format XYZ
98.4375 2.9416666666666669 1245
98.712499999999991 2.9416666666666669 1097
98.987499999999997 2.9416666666666669 619
99.262500000000003 2.9416666666666669 178
98.4375 2.625 1367
98.712499999999991 2.625 1239
98.987499999999997 2.625 1148
99.262500000000003 2.625 659
98.4375 2.3083333333333336 822
98.712499999999991 2.3083333333333336 1416
98.987499999999997 2.3083333333333336 1142
99.262500000000003 2.3083333333333336 1235

Twelve cells, twelve rows. A spreadsheet can read this.

B: Information from a vector file

Every question here is answered by one SQL query. Change the names in it for your own data.

B1: How many rows are there?

A CSV file is a vector file for GDAL, even without any shapes.

gdal vector sql towns.csv /vsistdout/ --output-format CSV --dialect SQLite --sql "select count(*) towns from towns"
towns
31

The name of the layer is the name of the file without its ending.

B2: Which values does a column have, and how often?

The first thing to do with a table you do not know.

gdal vector sql towns.csv /vsistdout/ --output-format CSV --dialect SQLite --sql "select kind, count(*) number from towns group by kind order by number desc"
kind,number
subdistrict seat,18
other place,7
district seat,6

group by makes one row for each value, and count(*) counts its rows. The kinds are those of the GeoNames list (ledger L92).

B3: Which three districts are the largest?

Sort, and stop after three.

gdal vector sql districts.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select name, round(st_area(geom,1)/1e6) km2 from district order by km2 desc limit 3"
name,km2
Simalungun,4405
Asahan,3780
Tapanuli Utara,3713

Without desc you would get the three smallest.

B4: How long is the border of each district?

st_boundary takes the line around a shape, and st_length measures it.

gdal vector sql districts.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select name, round(st_length(st_boundary(geom),1)/1000) km from district order by km desc"
name,km
Simalungun,502
Deli Serdang,451
Danau Toba,448
Asahan,380
Labuhan Batu Utara,355
Tapanuli Utara,354
Toba Samosir,349
Serdang Bedagai,315
Samosir,312
Karo,294
Humbang Hasundutan,262
Dairi,248
Pakpak Bharat,182
Kota Pematang Siantar,56

Be careful with this number. A border gets longer the more exactly it is drawn.

B5: Where is the middle of each district?

A label needs a place. st_pointonsurface gives a point that is always inside the shape.

gdal vector sql districts.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select name, round(st_x(st_pointonsurface(geom)),3) lon, round(st_y(st_pointonsurface(geom)),3) lat from district"
name,lon,lat
Asahan,99.62,2.848
Dairi,98.286,2.83
Danau Toba,98.902,2.611
Deli Serdang,98.718,3.478
Humbang Hasundutan,98.599,2.24
Karo,98.337,3.1
Kota Pematang Siantar,99.057,2.952
Labuhan Batu Utara,99.77,2.429
Pakpak Bharat,98.268,2.53
Samosir,98.57,2.544
Serdang Bedagai,99.001,3.347
Simalungun,98.784,2.952
Tapanuli Utara,99.065,1.995
Toba Samosir,99.335,2.386

The centre of gravity, st_centroid, can lie outside. For a lake around an island, it does.

B6: Which districts touch the lake?

The lake is one row of the table, and the others are compared with it.

gdal vector sql districts.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select a.name from district a, district b where b.name='Danau Toba' and a.name<>b.name and st_intersects(a.geom, b.geom)"
name
Dairi
Humbang Hasundutan
Karo
Samosir
Simalungun
Tapanuli Utara
Toba Samosir

The query uses the table twice, once as a and once as b.

C: A raster in another size or shape

The numbers stay heights. Only the cells change.

C1: Cells of exactly 100 metres

Degrees are not suitable for distances. Reproject to UTM, and give the width of the new cells.

gdal raster reproject toba.tif toba_utm.tif --dst-crs EPSG:32647 --resolution 100,100 -r average --overwrite

The relief of Lake Toba in grey, very slightly turned, in cells of 100 metres.

-r average is the right choice when cells become larger. For smaller cells take cubic, and for classes nearest or mode.

C2: Only the first 500 columns and rows

Test a command on a small part of the raster first.

gdal raster clip toba.tif first.tif --window 0,0,500,500 --overwrite

The window counts cells, not degrees: first column, first row, width, height.

C3: Cut along a border

Keep the cells inside one district, and nothing else.

gdal raster clip toba.tif samosir.tif --like districts.gpkg --like-where "name='Samosir'" --overwrite

The relief of the district Samosir: the long island, and a part of the western shore. Everything else is empty.

The district has the island and a piece of the shore in the west. --like-where chooses the row, as --where does elsewhere.

C4: Rotate the map until the lake is horizontal

Lake Toba runs from north-west to south-east. A projection may have any direction as its upper edge.

gdal raster reproject toba.tif turned.tif --dst-crs "+proj=omerc +lat_0=2.6 +lonc=98.85 +alpha=135 +gamma=0 +ellps=WGS84" -r cubic --overwrite

The relief turned by 45 degrees. The lake now lies from left to right.

alpha is the direction of the lake, 135 degrees on a compass, and gamma=0 makes this direction horizontal. Chapter 4 uses the same projection.

C5: Put a frame around a map

Clip with a window that is larger than the map.

gdal raster clip map.tif framed.tif --window -40,-40,2060,1790 --allow-bbox-outside-source --overwrite
Warning 1: -srcwin -40 -40 2060 1790 falls partially outside source raster extent. Pixels outside the source raster extent will be set to the NoData value (if defined), or zero.

The coloured map of Lake Toba with a black frame.

The window starts 40 cells outside the map. Cells that do not exist become 0, which is black. GDAL prints a message about this.

C6: How coarse can a map be?

Make 60 columns out of 1,980.

gdal raster resize map.tif coarse.tif --size 60,0 -r average --overwrite

The map of Lake Toba in large blurred squares. The blue ring around Samosir can still be seen.

The lake is still visible. A global climate model has even fewer cells for a lake like this.

D: A raster with other numbers

Here the cells stay, and the values change.

D1: From metres to feet

calc gives each raster a letter, and you write a formula.

gdal raster calc -i A=toba.tif -o feet.tif --calc "A*3.28084" --overwrite

One metre has 3.28084 feet.

D2: Heights above the lake instead of above the sea

Subtract the level of the water.

gdal raster calc -i A=toba.tif -o above.tif --calc "A-901" --overwrite

The lake is now 0, and the lowlands are negative.

D3: Which land lies less than 100 m above the water?

A question with yes or no becomes 1 or 0.

gdal raster calc -i A=toba.tif -o low.tif --calc "(A > 901 && A <= 1001) ? 1 : 0" --ot Byte --overwrite

White marks the land between 901 and 1,001 metres: a fringe around the lake, broad in the south-east and on Samosir, and a wide band on the outer slopes in the north-east.

&& is and. The question mark means: if this is true, then 1, otherwise 0. On the outer slopes there is land of the same height, too. The formula uses only the height, so it includes this land, too.

D4: Four classes instead of thousands of heights

reclassify takes a list of ranges.

gdal raster reclassify toba.tif classes.tif -m "[-100,901)=1; 901=2; (901,1500]=3; (1500,9000]=4" --ot Byte --overwrite

Four grey tones: lowland, lake, middle heights and mountains.

A square bracket includes the number, and a round one leaves it out. 1 is below the lake, 2 the lake itself, 3 the land up to 1,500 m, and 4 is higher.

D5: Remove very small areas

The classes have many tiny spots. sieve merges each small group with its largest neighbour.

gdal raster sieve classes.tif clean.tif --size-threshold 200 --overwrite

The same four tones, with smooth large areas and no small spots.

Groups of less than 200 cells are gone. So are the little blue spots of section 5.

D6: Smooth a relief

Each cell gets a weighted mean of itself and its neighbours.

gdal raster neighbors toba.tif smooth.tif --kernel gaussian --size 5 --overwrite

Contour lines from a smoothed relief have fewer small bends. Chapter 10 uses this.

D7: Find the edges

Another kernel gives large numbers where the values change quickly.

gdal raster neighbors shade.tif edges.tif --kernel edge1 --size 3 --overwrite

The programs that find edges in photographs start in the same way.

D8: What is the highest place within 1 km?

The neighbourhood may be larger, and the method may be max.

gdal raster neighbors toba_utm.tif around_max.tif --method max --kernel equal --size 21 --overwrite

The relief as if built from pale squares: each summit has spread into a block of two kilometres.

21 cells of 100 m: ten to each side, and the cell itself. Every summit becomes a square.

D9: Remove the lake

Give the water a number that means “no data”.

gdal raster calc -i A=toba.tif -o dry.tif --calc "A==901 ? -9999 : A" --nodata -9999 --overwrite

== tests whether two values are equal. --nodata writes into the file that -9999 is not a height.

D10: Fill a hole from its edges

fill-nodata estimates the missing cells from the ones around them.

gdal raster fill-nodata dry.tif filled.tif --max-distance 400 --smoothing-iterations 10 --overwrite

Good for small gaps in a satellite picture. For a lake of 1,100 km2 the result is not reliable. The real floor of Lake Toba lies up to about 500 m below the water (ledger L92).

D11: How far is it to the lake, from anywhere?

proximity gives each cell its distance to the nearest cell with a certain value.

gdal raster proximity clean.tif far.tif --target-values 2 --distance-units pixel --overwrite

The distance to the lake as a grey ramp: black on the water, and paler outwards in rounded rings. The middle of Samosir is a little paler than its shore.

The distance is counted in cells of 60 m. The value 2 is the lake in our classes. Chapter 8 is about this command.

E: Light, slope and the form of the land

Each of these commands reads a relief and calculates one property of its form.

E1: Evening light

The light comes from the west, and the sun is low above the horizon.

gdal raster hillshade toba.tif evening.tif --azimuth 270 --altitude 20 --overwrite

The relief with low light from the left. The land is dark, and only western slopes are bright.

azimuth is the direction on a compass, and altitude the height of the sun in degrees.

E2: Light from several sides

With light from one direction, some slopes are black. This variant uses several directions.

gdal raster hillshade toba.tif soft_light.tif --variant multidirectional --overwrite

A softer relief, with detail also on the slopes that face away.

This is a good background for a map with many colours.

E3: Make small hills visible

If the heights are multiplied, small hills get a visible shade, too.

gdal raster hillshade toba.tif strong.tif -z 4 --overwrite

A harsh relief. Even the gentle slopes in the north-east show every valley.

-z 4 makes everything four times as high. Mountains become too dark, and small forms in the plains become visible.

E4: How steep is it?

slope gives the result in degrees, or in percent.

gdal raster slope toba.tif steep.tif --unit percent --overwrite

Steep land is pale: the walls around the lake form a bright, broken ring.

100 percent is 45 degrees. The ring is the steep inner slope of the crater.

E5: In which direction does each slope face?

aspect gives a direction: 0 is north, 90 east, 180 south and 270 west.

gdal raster aspect toba.tif facing.tif --overwrite

Useful for sun and shade on fields. Flat cells have no direction, and get “no data”. Chapter 11 uses aspect for other data.

E6: How rough is it?

The difference between the highest and the lowest of nine neighbouring cells.

gdal raster roughness toba.tif rough.tif --overwrite

The walls and the eroded mountains are bright, and the plateaus are nearly black.

The difference is small on plateaus, and large in the mountains in the east.

E7: Ridges and valleys

The topographic position index compares a cell with the mean of its neighbours.

gdal raster tpi toba.tif position.tif --overwrite

Above zero is a ridge or a summit, below zero a valley, and near zero a plain or an even slope.

E8: Draw the shore

One contour line at one height, half a metre above the water.

gdal raster contour toba.tif shore.gpkg --levels 901.5 --elevation-name height --overwrite

The shore of the lake and of Samosir as a dark line, and the same height as a long wiggly line on the outer slopes in the north and the south.

The line of 901.5 m also runs around the mountains outside, because the land falls through this height there once more.

E9: Areas between heights

With --polygonize the spaces between the lines become polygons.

gdal raster contour toba.tif bands.gpkg --levels "MIN,500,1000,1500,2000,MAX" --polygonize --min-name low --max-name high --overwrite

Nested areas with dark borders, one for each band of height.

Each polygon has its lowest and highest level in the table. Now you can colour them, or calculate their area.

E10: What can you see from the top of a volcano?

Pusuk Buhit stands on the west shore of the lake (ledger L92). viewshed tests every line of sight. It needs metres, so the line uses the UTM relief.

gdal raster viewshed toba_utm.tif seen.tif --position 461610,287522 --height 2 --overwrite

White is visible from the volcano: the north-west of the lake, a wide area of water in the south, the western slope of Samosir, and the walls of the crater at the far ends. The east side behind Samosir is black.

The white cells are visible for a person whose eyes are 2 m above the top. Chapter 12 explains this in detail.

F: Satellite images

The file scene.tif is a part of two Sentinel-2 images of 3 October 2021, in cells of 100 m (ledger L95). It has five bands: blue, green, red, near infrared and short-wave infrared.

F1: What does the satellite measure at one place?

Five numbers for one cell, in the forest of Samosir.

gdallocationinfo -valonly -wgs84 scene.tif 98.83 2.6
164
349
192
2745
1145

Plants reflect little red light (the third number) and a lot of near infrared (the fourth). Our eyes cannot see that.

F2: Natural colours

A screen needs red, green and blue. In this file they are the bands 3, 2 and 1.

gdal raster select scene.tif natural.tif --band 3,2,1 --overwrite

If you open it now, it may be black. The numbers go up to 12,000, and a screen expects 0 to 255.

F3: Make it bright enough

The values from 0 to 2,500 are scaled to the whole range of the screen.

gdal raster scale natural.tif natural8.tif --ot Byte --src-min 0 --src-max 2500 --dst-min 0 --dst-max 255 --overwrite

Lake Toba from space: dark water with bright streaks, green land with brown fields, a few white clouds in the east. The upper right corner is black.

The bright streaks are the sun on the water. The corner at the upper right is empty, because there the image ends.

F4: Plants in bright green

Two steps in one line: select other bands, and scale them.

gdal raster pipeline read scene.tif ! select --band 5,4,3 ! scale --ot Byte --src-min 0 --src-max 4000 --dst-min 0 --dst-max 255 ! write false.tif --overwrite

The same image in strong colours: plants are bright green, bare fields pink and orange, and water is black.

Short-wave infrared becomes red, near infrared green, and red blue. Bare soil is pink now, and it is easy to find.

F5: Make the dark parts brighter

An exponent below 1 makes the dark parts brighter, and changes the bright ones less.

gdal raster scale natural.tif lifted.tif --ot Byte --src-min 0 --src-max 2500 --dst-min 0 --dst-max 255 --exponent 0.5 --overwrite

The image in pale colours. The water shows bands and swirls.

Differences within the water are now visible.

F6: How green is it? (NDVI)

Near infrared minus red, divided by their sum. A[4] is the fourth band.

gdal raster calc -i A=scene.tif -o ndvi.tif --flatten --calc "(A[4]-A[3])/(A[4]+A[3])" --propagate-nodata --nodata -9999 --overwrite

Dense plants are pale, fields grey, and water and clouds dark.

The result lies between -1 and 1. --flatten makes one band out of five. With --propagate-nodata the empty corner stays empty, and --nodata -9999 gives it a number that no plant can have.

F7: The same with colours for soil, plants and water

Brown for bare, green for plants, blue for water.

gdal raster color-map ndvi.tif ndvi_colour.tif --color-map ndvi.txt --overwrite

A map of plants: dark green forests, yellowish fields and a blue lake.

Water has a negative value, so the file ndvi.txt can give it a colour of its own.

F8: Where is water?

Water reflects more green light than near infrared. Land does the opposite.

gdal raster calc -i A=scene.tif -o water.tif --flatten --calc "A[2] > A[4] ? 1 : 2" --ot Byte --propagate-nodata --overwrite

The lake in black on a white ground, and a few black spots in the clouds.

1 is water and 2 is land. This method uses only the image, and the relief shows the lake by its height of 901 m. For 99.4 percent of the cells, both give the same result.

F9: From stored numbers to real ones

Satellite files store whole numbers to save room. The manual gives a factor.

gdal raster calc -i A=scene.tif -o reflect.tif --calc "A*0.0001" --ot Float32 --propagate-nodata --overwrite

Here 10,000 means that all light comes back. Other products have other factors: the land temperature of MODIS has 0.02, and is in kelvin then (ledger L97).

F10: Make the empty corner transparent

The file has a note that 0 means “no data”. A web browser does not read this note.

gdal raster nodata-to-alpha natural8.tif clear.tif --overwrite

The natural image. The empty corner has disappeared.

The new band says for each cell whether it can be seen.

F11: Sharpen

The opposite of smoothing: small differences get larger.

gdal raster neighbors natural8.tif sharp.tif --kernel unsharp-masking --size 5 --ot Byte --overwrite

The natural image with harder edges along the fields and the shore.

Use this for a printed picture. Do not calculate with such an image.

F12: Two rasters on the same grid

The relief is in degrees, and the image in metres. To calculate with both, their cells must have the same positions.

gdal raster reproject toba.tif fit.tif --dst-crs EPSG:32647 --bbox 440000,255000,515000,322000 --size 750,670 -r average --overwrite

The box and the size are those of scene.tif. You find them with gdal raster info.

F13: Forest above 1,500 m

Two rasters in one formula, with the letters N and H.

gdal raster calc -i N=ndvi.tif -i H=fit.tif -o high_forest.tif --calc "(N > 0.8 && H > 1500) ? 1 : 0" --ot Byte --nodata 255 --overwrite

White areas on black: the mountains in the west, the ridge of Samosir and some heights in the east.

Without the line before, GDAL would stop with an error, because the extents are not the same. This prevents wrong results.

G: NetCDF: many dates in one file

Weather and climate data comes as a cube: a map for each date, all in one file. rain.nc has the rain of the twelve months of 2023 over Sumatra, from CHIRPS3 (ledger L94).

G1: What is in this file?

Such a file often has several variables. GDAL calls them subdatasets.

gdal raster info rain.nc
Driver: netCDF/Network Common Data Format
Files: rain.nc
Size is 512, 512
Metadata:
  NC_GLOBAL#Conventions=CF-1.8
  NC_GLOBAL#source=Cut from CHIRPS v3.0, Climate Hazards Center, UC Santa Barbara
  NC_GLOBAL#title=Monthly rainfall over Sumatra, 2023
Subdatasets:
  SUBDATASET_1_NAME=NETCDF:"rain.nc":precip
  SUBDATASET_1_DESC=[12x260x230] precip (16-bit integer)
  SUBDATASET_2_NAME=NETCDF:"rain.nc":land
  SUBDATASET_2_DESC=[260x230] land (8-bit integer)
Corner Coordinates:
Upper Left  (    0.0,    0.0)
Lower Left  (    0.0,  512.0)
Upper Right (  512.0,    0.0)
Lower Right (  512.0,  512.0)
Center      (  256.0,  256.0)

There are two. precip has 12 maps of 260 rows and 230 columns, and land has one. The strange names with NETCDF: are what you write to open one of them.

G2: One variable as a GeoTIFF

The quotes of the list are not needed.

gdal raster convert NETCDF:rain.nc:precip rain.tif --overwrite

The twelve months are now twelve bands.

G3: The file has no coordinate system

Many netCDF files have latitudes and longitudes, but no coordinate system. Add it.

gdal raster edit rain.tif --crs EPSG:4326

Without this, the commands that use longitude and latitude would not work. edit writes into the file, and no number changes.

G4: Only March

March is the third band.

gdal raster select rain.tif march.tif --band 3 --overwrite

Rain in March 2023 over Sumatra and Malaysia in grey. The south of Sumatra is the palest, and the north-east of Malaysia the darkest.

The same works on the netCDF file directly: NETCDF:rain.nc:precip in place of rain.tif.

G5: Only March, and still a netCDF file

gdal mdim works with all dimensions of the cube: time, rows and columns.

gdal mdim convert rain.nc march.nc --array "name=precip,view=[2,:,:]" --overwrite

The view counts from 0, so March is 2. A colon means all: all rows, and all columns.

G6: January to March by their dates

The time is stored as days since 1 January 2023. Take the days 0 to 59.

gdal mdim convert rain.nc quarter.nc --array precip --subset "time(0,59)" --overwrite

lat(1,4) and lon(98,100) cut the map in the same way.

G7: The whole year at one place

Lake Toba again. One number for each month, from January to December, in millimetres.

gdallocationinfo -valonly -wgs84 rain.tif 98.95 2.65
316
140
205
121
159
65
100
201
168
258
323
200

The driest month is June, and the wettest is November. Copy the numbers into a spreadsheet, and you have a diagram.

G8: The rain of the whole year

--flatten goes through all bands of each cell, and sum adds them up.

gdal raster calc -i A=rain.tif -o year_wrong.tif --flatten --calc "sum(A)" --overwrite

A picture of two tones: the sea is black, and all land is white.

This result is wrong. Over the sea there is no data, stored as -9999. The formula has added twelve of them, and the sea has -119,988 mm now.

G9: The same, and “no data” stays “no data”

One more option, and it belongs to nearly every calculation with real data.

gdal raster calc -i A=rain.tif -o year.tif --flatten --calc "sum(A)" --propagate-nodata --overwrite

The rain of the year 2023 in grey. The brightest area is in the east of Malaysia, and there are bright spots in the west and north of Sumatra. The sea is black.

If one month has no data, the sum of the year has no data, too. Now the values go from 1,234 to 6,204 mm.

G10: The mean, the driest and the wettest month of each cell

Some functions are built in. Put the word mean, min or max after --calc.

gdal raster calc -i A=rain.tif -o mean.tif --flatten --dialect builtin --calc mean --overwrite

The built-in ones are fast, and take care of “no data” by themselves. But sum gives 0 and not “no data” over the sea, so look at the result. We need the other two in a moment:

gdal raster calc -i A=rain.tif -o min.tif --flatten --dialect builtin --calc min --overwrite

gdal raster calc -i A=rain.tif -o max.tif --flatten --dialect builtin --calc max --overwrite

G11: How many months had more than 200 mm?

In two steps. First a 1 for each wet month:

gdal raster calc -i A=rain.tif -o is_wet.tif --calc "A > 200" --propagate-nodata --overwrite

That makes twelve bands of 0 and 1. Now add them up:

G12: Add them up

The line of the yearly rain, with another file.

gdal raster calc -i A=is_wet.tif -o wet_months.tif --flatten --calc "sum(A)" --propagate-nodata --overwrite

The number of wet months in grey, in steps. Many in the west of Sumatra and in parts of Malaysia, and few in the dark areas between.

Why not sum(A > 200) in one line? It runs, but the result is wrong, because the comparison is applied only to the last month (ledger L93). Test a formula at one place where you know the answer.

G13: Was March wetter or drier than usual?

Here usual is only the mean of this one year. With a mean of thirty years, the line is the same.

gdal raster calc -i A=march.tif -i M=mean.tif -o anomaly.tif --calc "A-M" --propagate-nodata --overwrite

March minus the mean in grey: pale in the south of Sumatra, and darkest in the east of Malaysia.

Positive is wetter. This is called an anomaly. For a ratio in percent write 100*A/M.

G14: On a scale from 0 to 100

0 is the driest month of the year at this place, and 100 the wettest.

gdal raster calc -i A=march.tif -i L=min.tif -i H=max.tif -o index.tif --calc "100*(A-L)/(H-L)" --propagate-nodata --overwrite

March between the driest and the wettest month, in grey: bright in the south of Sumatra, black in the north-east of Malaysia.

The vegetation condition index (VCI) has this form, with the lowest and the highest value of many years (ledger L97).

G15: The rain of each district

A raster from a netCDF file is a raster like any other.

gdal raster zonal-stats year.tif /vsistdout/ --output-format CSV --zones districts.gpkg --include-field name --stat mean
name,mean
Asahan,2275.77952755906
Dairi,2347.703125
Danau Toba,2137.71428571429
Deli Serdang,2440.21590909091
Humbang Hasundutan,2660.03703703704
Karo,2454.73913043478
Kota Pematang Siantar,2704.66666666667
Labuhan Batu Utara,2505.70175438596
Pakpak Bharat,2965.61904761905
Samosir,2053.7380952381
Serdang Bedagai,2397.12903225806
Simalungun,2396.77304964539
Tapanuli Utara,2483.34166666667
Toba Samosir,2499.4

Millimetres in 2023. One cell is about 5.5 km wide, so a small district has only a few of them.

G16: Back to netCDF

The ending .nc is enough.

gdal raster convert year.tif year.nc --overwrite

The variable gets the name Band1. Programs for climate data can read it.

H: HDF5: a file without coordinates

Many products of satellite agencies are HDF5 files. The format can store many kinds of data, and it has no fixed place for coordinates. sea.h5 has the temperature of the sea around Java on 1 September 2019 (ledger L96), and was made without coordinates, as an example of such files.

H1: What is in this file?

These lines use the older programs. On the computer of this tutorial, the new one stops on HDF5 files without a message (ledger L93).

gdalinfo sea.h5
Driver: HDF5Image/HDF5 Dataset
Files: sea.h5
Size is 700, 360
Metadata:
  source=Cut from CoralTemp v3.1, NOAA Coral Reef Watch
Image Structure Metadata:
  COMPRESSION=DEFLATE
Corner Coordinates:
Upper Left  (    0.0,    0.0)
Lower Left  (    0.0,  360.0)
Upper Right (  700.0,    0.0)
Lower Right (  700.0,  360.0)
Center      (  350.0,  180.0)
Band 1 Block=175x45 Type=Int16, ColorInterp=Undefined
  Metadata:
    east=130
    empty=-32768
    long_name=sea surface temperature, 1 September 2019
    north=2
    south=-16
    units=0.01 degrees Celsius
    west=95

Read the notes at the end. The limits are there: west 95, east 130, north 2, south -16. The unit is a hundredth of a degree Celsius, and -32768 is empty. But the corner coordinates are only cell numbers.

H2: Add the coordinates

Coordinate system, corners and the empty value, all in one line.

gdal_translate -q -a_srs EPSG:4326 -a_ullr 95 2 130 -16 -a_nodata -32768 HDF5:sea.h5://science/sst sst.tif

The sea around Java in grey. The land is empty. South of Java lies a dark band of cold water with long streaks to the south.

-a_ullr takes the upper left corner and then the lower right one. HDF5:sea.h5://science/sst is the file, and the path inside it.

H3: Degrees Celsius

The factor from the notes.

gdal raster calc -i A=sst.tif -o celsius.tif --calc "A*0.01" --ot Float32 --propagate-nodata --overwrite

The values go from 21.0 to 30.3 degrees. These are plausible temperatures for a tropical sea. Always check the values in this way.

H4: Degrees Fahrenheit

Multiply by 1.8 and add 32.

gdal raster calc -i C=celsius.tif -o fahrenheit.tif --calc "C*1.8+32" --propagate-nodata --overwrite

For kelvin, add 273.15 to the Celsius values.

H5: Why is my map upside down?

The same file can also be opened as netCDF, because netCDF files are HDF5 files inside.

gdal raster convert NETCDF:sea.h5:/science/sst upside.tif --overwrite

The same area upside down, in black and white: Borneo hangs below Java, and Sumatra is at the lower left.

netCDF files often start in the south, so GDAL turns them if they contain no information about the order. This one starts in the north, and turning it is wrong. Always check the position of a place that you know.

H6: Do not turn it

This option prevents it.

gdal raster convert NETCDF:sea.h5:/science/sst upright.tif --config GDAL_NETCDF_BOTTOMUP=NO --overwrite

--config changes a setting of GDAL for one line. Now add the coordinates as before: gdal raster edit upright.tif --crs EPSG:4326 --bbox 95,-16,130,2.

I: Pictures and files for other people

The same map in formats for different uses.

I1: A table for a spreadsheet

XYZ with a header and commas is a CSV file.

gdal raster convert tiny.tif tiny.csv --output-format XYZ --co ADD_HEADER_LINE=YES --co COLUMN_SEPARATOR=COMMA --overwrite

In older versions of GDAL, gdal2xyz.py does this. Use a small raster, because every cell becomes a row.

I2: A plain binary file with a header

Some older programs for images read only numbers, and a small text file that explains them.

gdal raster convert toba.tif toba.img --output-format ENVI --overwrite

The numbers are in toba.img, and the explanation is in toba.hdr. GDAL reads such a pair as it reads everything else, so the way back is the same command.

I3: A small picture for an e-mail

JPEG is made for photographs and shaded maps.

gdal raster convert map.tif map.jpg --co QUALITY=80 --overwrite

--co sets an option of the output format. Here it is the quality, from 1 to 100.

I4: The same file, but smaller

A GeoTIFF is not compressed unless you ask.

gdal raster convert toba.tif toba_small.tif --co COMPRESS=DEFLATE --co PREDICTOR=2 --overwrite

6.8 MB become 2.8 MB, and nothing is lost. PREDICTOR=2 stores the differences between neighbours, which are small in a relief.

I5: Write a note into a file

Who made it, when, from what? A file can carry such notes.

gdal raster edit toba_small.tif --metadata SOURCE=Copernicus --metadata MADE_IN=Chapter_0

edit changes the file itself and makes no new one. gdal raster info shows the notes. gdal vector edit does the same for vector files.

I6: A file for the cloud

A Cloud Optimized GeoTIFF is ordered so that a program can read a small piece of it over the internet.

gdal raster convert map.tif map_cog.tif --output-format COG --co COMPRESS=DEFLATE --overwrite

Other programs can read it as a normal GeoTIFF. The relief of these chapters comes from such files.

I7: A map for Google Earth

KMZ is a zip with pictures and their places.

gdal raster convert map.tif map.kmz --output-format KMLSUPEROVERLAY --co FORMAT=JPEG --overwrite

Open it with a double click, and the map appears on the globe.

I8: Tiles for a web page

A web map loads small square pictures. This line cuts them all, and writes a page that shows them.

gdal raster tile map.tif tiles --min-zoom 8 --max-zoom 10

Open tiles/leaflet.html in a browser. The page needs the internet for the small program that moves the map.

I9: Only 16 colours

With fewer colours, the file is smaller.

gdal raster rgb-to-palette map.tif poster.tif --color-count 16 --overwrite

The map of Lake Toba in 16 colours, with hard steps between them.

GDAL selects the 16 colours from the colours of the map.

I10: Slope, shade and height as red, green and blue

A colour picture is three rasters on top of each other. They may be any three. All three have to run from 0 to 255 first. The shade does already:

gdal raster scale steep.tif steep8.tif --ot Byte --src-min 0 --src-max 100 --dst-min 1 --dst-max 255 --overwrite

gdal raster scale toba.tif grey8.tif --ot Byte --src-min 0 --src-max 2500 --dst-min 1 --dst-max 255 --overwrite

Then:

gdal raster stack steep8.tif shade.tif grey8.tif three.tif --overwrite

A strange colourful relief: steep walls in red and pink, plateaus in cyan, lowlands and the lake in green.

Steep land is red, sunny land is green and high land is blue, and they mix. Such a picture needs an explanation, but it shows three properties at once. The line before scaled the three rasters to 0 to 255.

J: Rows and columns

What you would do in a spreadsheet.

J1: Keep some columns

select with the names you want.

gdal vector select towns.csv /vsistdout/ --output-format CSV "name,kind"
name,kind
Ambarita,subdistrict seat
Balige,district seat
Dolok Sanggul,district seat
Harian,subdistrict seat
Lintongnihuta,subdistrict seat
Mogang,subdistrict seat
Muara,subdistrict seat
Nainggolan,other place
Onan Ganjang Satu,subdistrict seat
Pakkat,subdistrict seat
Pane Tongah,subdistrict seat
Pangururan,district seat
Parapat,subdistrict seat
Parlilitan,subdistrict seat
Parmonangan,other place
Paropo,other place
Pematang Raya,district seat
Pematangsiantar,other place
Salak,district seat
Saribudolok,subdistrict seat
Sarimatondang,subdistrict seat
Siborong-Borong,subdistrict seat
Sidikalang,district seat
Sipintuangin,subdistrict seat
Sondi,subdistrict seat
Sukarama,subdistrict seat
Sumbul,subdistrict seat
Tigarunggu,subdistrict seat
Tomok Bolon,other place
Tongging,other place
Tuktuk Sonak,other place

With --exclude it keeps all the others.

J2: Keep some rows

filter with a condition that is true or false.

gdal vector filter towns.csv /vsistdout/ --output-format CSV --where "kind='district seat'"
name,kind,lon,lat
Balige,district seat,"99.0657","2.3328"
Dolok Sanggul,district seat,"98.7501","2.2588"
Pangururan,district seat,"98.6961","2.6081"
Pematang Raya,district seat,"98.8473","2.9658"
Salak,district seat,"98.3235","2.5566"
Sidikalang,district seat,"98.3127","2.74899"

Other useful words are and, or, not, is null and in ('A','B').

J3: All names that start with Pa

substr cuts a piece out of a text: from letter 1, two letters.

gdal vector filter towns.csv /vsistdout/ --output-format CSV --where "substr(name,1,2)='Pa'"
name,kind,lon,lat
Pakkat,subdistrict seat,"98.4745","2.1524"
Pane Tongah,subdistrict seat,"98.9723","2.9059"
Pangururan,district seat,"98.6961","2.6081"
Parapat,subdistrict seat,"98.9349","2.663"
Parlilitan,subdistrict seat,"98.4571","2.324"
Parmonangan,other place,"99.0515","2.397"
Paropo,other place,"98.5211","2.8663"

Many examples use like 'Pa%'. The percent sign has a meaning of its own in some shells, so this series avoids it.

J4: Sort by a column

From south to north.

gdal vector sql towns.csv /vsistdout/ --output-format CSV --dialect SQLite --sql "select name, lat from towns order by cast(lat as real) limit 5"
name,lat
Pakkat,"2.1524"
Onan Ganjang Satu,"2.1589"
Siborong-Borong,"2.21251"
Dolok Sanggul,"2.2588"
Lintongnihuta,"2.276"

A CSV has only text. cast(lat as real) makes a number of it, or 10 would come before 9.

J5: Give a column a new name, and add another one

Write the old name and then the new one.

gdal vector sql towns.csv /vsistdout/ --output-format CSV --dialect SQLite --sql "select name place, upper(name) label, kind='district seat' seat from towns limit 4"
place,label,seat
Ambarita,AMBARITA,0
Balige,BALIGE,1
Dolok Sanggul,DOLOK SANGGUL,1
Harian,HARIAN,0

upper writes capitals. A comparison becomes 1 or 0.

K: Points, tables and devices

Much everyday data is stored in tables.

K1: From a table to points

Say which columns hold the position, and what kind of coordinates they are.

gdal vector make-point towns.csv towns.gpkg --x lon --y lat --dst-crs EPSG:4326 --overwrite

31 dots, spread over the area, with a small group in the middle on the east side of Samosir.

31 towns and villages from GeoNames (ledger L92). x is the longitude. If your points land in the wrong ocean, the two are exchanged.

K2: From points to a table

This is the opposite conversion. AS_XY writes the position into two columns.

gdal vector convert towns.gpkg towns_xy.csv --lco GEOMETRY=AS_XY --overwrite

--lco sets an option of the new layer, and --co sets an option of the file.

K3: An Excel file

The ending is enough.

gdal vector convert towns.gpkg towns.xlsx --overwrite

It also reads Excel files, with each sheet as a layer. .ods is the one for LibreOffice.

K4: An Esri geodatabase

The format of ArcGIS. It is a folder that looks like a file.

gdal vector convert districts.gpkg districts.gdb --overwrite

The ending .gdb is enough, and no Esri software is needed.

K5: Points for a GPS device

GPX is a format for GPS watches and phones.

gdal vector convert towns.gpkg towns.gpx --co GPX_USE_EXTENSIONS=YES --overwrite

The towns become waypoints with their names.

K6: A file for Google Earth or a phone

KML has been around for a long time, and nearly everything opens it.

gdal vector convert towns.gpkg towns.kml --output-format LIBKML --overwrite

KML always uses longitude and latitude. GDAL converts the coordinates if necessary.

K7: A shapefile, if somebody asks for one

An old format that is still used very often.

gdal vector convert districts.gpkg districts.shp --overwrite

It is four files or more, and they belong together. Column names have ten letters at most.

K8: Short coordinates for a web page

Four decimals are about 11 m. More only makes the file larger.

gdal vector convert districts.gpkg short.geojson --lco COORDINATE_PRECISION=4 --overwrite

141 kB become 83 kB.

K9: Pack a file into a zip, and go on using it

GDAL reads inside a zip, so you need not unpack it again.

gdal vsi sozip create districts.geojson districts.geojson.zip --overwrite
Adding districts.geojson... (1/1)

From now on /vsizip/districts.geojson.zip works wherever a file name does.

L: New shapes from old ones

Points, lines and polygons can be made from each other.

L1: A simpler border

Leave out points that hardly matter.

gdal vector simplify districts.gpkg simple.geojson --tolerance 0.02 --overwrite

The districts with straight, angular borders. Small gaps and overlaps show where neighbours no longer fit.

Each district is simplified alone, so neighbours no longer fit exactly.

L2: A simpler border without gaps

The same, but neighbours keep one common line.

gdal vector simplify-coverage districts.gpkg simple_fit.gpkg --tolerance 0.02 --overwrite

The districts with simple borders that fit together everywhere.

Chapter 7 is about the difference.

L3: One shape out of many

st_union merges all rows into one, and the inner borders are removed.

gdal vector sql districts.gpkg whole_area.gpkg --dialect SQLite --sql "select st_union(geom) geom from district" --output-layer whole_area --overwrite

One large shape without inner borders.

With group by and a column you get one shape for each value, such as one for each province.

L4: A box around each shape

Good for a quick test of where things are.

gdal vector sql districts.gpkg boxes.gpkg --dialect SQLite --sql "select name, st_envelope(geom) geom from district" --output-layer boxes --overwrite

Fourteen overlapping rectangles.

This is also how a spatial index works: it compares the boxes first, because that is fast.

L5: The convex hull of all towns

The convex hull is the smallest convex polygon that contains all points. It has no corner that points inwards.

gdal vector sql towns.gpkg band.gpkg --dialect SQLite --sql "select st_convexhull(st_collect(geometry)) geom from towns" --output-layer band --overwrite

A polygon with few corners. Its corners are the outermost towns.

st_collect puts all points together first.

L6: Only the lines

Borders as lines can have their own colour and width.

gdal vector sql districts.gpkg outline.gpkg --dialect SQLite --sql "select name, st_boundary(geom) geom from district" --output-layer outline --overwrite

Every inner border is there twice, once for each neighbour. Chapter 7 shows how to get each one once.

L7: A grid of hexagons

Hexagons are often used to count points per cell.

gdal vector sql lake_utm.gpkg net.gpkg --dialect SQLite --sql "select st_hexagonalgrid(geom, 3000) geom from district" --output-layer net --overwrite

The lake covered by a grid of hexagons, which has the form of a ring.

The sides are 3 km long, because the layer is in metres.

L8: One row for each hexagon

The whole grid is one row. This line writes each hexagon into its own row.

gdal vector explode-collections net.gpkg cells.gpkg --overwrite

The same command splits a country into its islands.

L9: Is every shape valid?

A polygon that crosses itself causes errors in later steps. Check for this first.

gdal vector check-geometry simple.geojson faults.geojson --overwrite

The file has a point and a reason for each fault. gdal vector make-valid repairs them.

M: Two files together

Cut one layer with another, or put both together.

M1: Cut a layer with a box

West, south, east, north.

gdal vector clip districts.gpkg window.gpkg --bbox 98.4,2.3,99.2,2.95 --overwrite

The districts cut off straight at the edges of a rectangle around the lake.

filter --bbox is different: it keeps the whole shape if it touches the box.

M2: Keep what lies inside another layer

Only the parts of the districts within 5 km of the lake. The shape of section 7 is in metres, and the districts are in degrees:

gdal vector reproject near_lake.geojson near_wgs.gpkg --dst-crs EPSG:4326 --overwrite

Then:

gdal vector layer-algebra intersection districts.gpkg near_wgs.gpkg inside.gpkg --overwrite

A ring around the lake, 5 km wide, cut into pieces by the borders of the districts.

layer-algebra does not change coordinate systems, so both layers must have the same one. The line before took care of that.

M3: Keep what lies outside

The same with erase.

gdal vector layer-algebra erase districts.gpkg near_wgs.gpkg outside.gpkg --overwrite

The districts with a large hole in the form of the lake and its surroundings. Inside the hole lies a small rest of Samosir.

The small island in the hole is the middle of Samosir again.

M4: Two layers into one file

The layers stay separate inside the file.

gdal vector concat towns.gpkg districts.gpkg both.gpkg --overwrite

A GeoPackage can hold many layers. The towns and the districts are now in one file. If you want all rows in one layer, add --mode single. This is what ogrmerge -single did.

M5: Which district is each town in?

A join by place and not by a number. Both layers are in both.gpkg now.

gdal vector sql both.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select t.name town, d.name district from towns t join district d on st_contains(d.geom, t.geometry) order by 2, 1"
town,district
Paropo,Dairi
Sidikalang,Dairi
Sumbul,Dairi
Muara,Danau Toba
Parapat,Danau Toba
Tuktuk Sonak,Danau Toba
Dolok Sanggul,Humbang Hasundutan
Lintongnihuta,Humbang Hasundutan
Onan Ganjang Satu,Humbang Hasundutan
Pakkat,Humbang Hasundutan
Parlilitan,Humbang Hasundutan
Tongging,Karo
Pematangsiantar,Kota Pematang Siantar
Salak,Pakpak Bharat
Sukarama,Pakpak Bharat
Ambarita,Samosir
Harian,Samosir
Mogang,Samosir
Nainggolan,Samosir
Pangururan,Samosir
Tomok Bolon,Samosir
Pane Tongah,Simalungun
Pematang Raya,Simalungun
Saribudolok,Simalungun
Sarimatondang,Simalungun
Sipintuangin,Simalungun
Sondi,Simalungun
Tigarunggu,Simalungun
Siborong-Borong,Tapanuli Utara
Balige,Toba Samosir
Parmonangan,Toba Samosir

order by 2, 1 sorts by the second column, and then by the first.

M6: How many towns lie in each district?

The same join, and one row for each district.

gdal vector sql both.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select d.name, count(t.name) towns from district d left join towns t on st_contains(d.geom, t.geometry) group by d.name order by towns desc"
name,towns
Simalungun,7
Samosir,6
Humbang Hasundutan,5
Danau Toba,3
Dairi,3
Toba Samosir,2
Pakpak Bharat,2
Tapanuli Utara,1
Kota Pematang Siantar,1
Karo,1
Serdang Bedagai,0
Labuhan Batu Utara,0
Deli Serdang,0
Asahan,0

left join keeps the districts without a town. With the hexagons, this makes a map of where people live.

M7: How far is each town from the lake?

Draw the shortest line from each town to the lake, and measure it. The 1 at the end means: on the curved Earth.

gdal vector sql both.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select t.name, round(st_length(st_shortestline(t.geometry, d.geom),1)/1000,1) km from towns t, district d where d.name='Danau Toba' order by km"
name,km
Parmonangan,0
Tuktuk Sonak,0
Muara,0.1
Paropo,0.1
Harian,0.2
Pangururan,0.2
Tongging,0.2
Ambarita,0.3
Nainggolan,0.3
Tomok Bolon,0.3
Mogang,0.4
Parapat,0.4
Balige,0.6
Sipintuangin,2
Tigarunggu,5.2
Lintongnihuta,5.8
Saribudolok,6.1
Dolok Sanggul,11.3
Siborong-Borong,12.4
Sarimatondang,14.8
Sumbul,15.6
Pematang Raya,19.2
Sondi,20.8
Pane Tongah,22.6
Sidikalang,24.4
Onan Ganjang Satu,28.5
Sukarama,30
Pematangsiantar,33.1
Salak,33.9
Parlilitan,34.2
Pakkat,43.3

A 0 means that the point of the town lies inside the polygon of the lake, or very close to it. Both files are only approximate.

M8: Lay one picture over another, half transparent

--opacity is in percent.

gdal raster blend colour.tif shade.tif light_map.tif --opacity 40 --overwrite

The map of Lake Toba in pale colours with a soft grey shade.

Paler than hsv-value in section 5. The second file lies on top, with 40 percent of its strength.

M9: Paste a piece into a larger raster

update changes the second file. So it works on a copy. First the copy:

gdal raster convert toba.tif paste.tif --overwrite

Then:

gdal raster update corner.tif paste.tif

corner.tif is the piece of section 3. In practice, you would use this for a newer relief of a small area.

N: Many files from one, one from many

N1: A file for each value

Split the districts by their code.

gdal vector partition districts.gpkg by_code --field code --scheme flat --output-format GPKG --overwrite

A folder with 14 files, one for each district. The next line looks into it.

N2: What is in a folder?

GDAL can list folders, also inside a zip or on a web server.

gdal vsi list by_code --output-format text
district_ID1205_0000000001.gpkg
district_ID1206_0000000001.gpkg
district_ID1208_0000000001.gpkg
district_ID1209_0000000001.gpkg
district_ID1210_0000000001.gpkg
district_ID1211_0000000001.gpkg
district_ID1212_0000000001.gpkg
district_ID1215_0000000001.gpkg
district_ID1216_0000000001.gpkg
district_ID1217_0000000001.gpkg
district_ID1218_0000000001.gpkg
district_ID1223_0000000001.gpkg
district_ID1273_0000000001.gpkg
district_ID1288_0000000001.gpkg

The names have the layer, the value and a number.

N3: A mosaic in a very small file

With the ending .vrt, GDAL writes only a note about where the tiles are.

gdal raster mosaic west.tif east.tif light.vrt --overwrite

It is 1.4 kB of text, and works like a raster. The tiles must stay where they are.

N4: A map of your rasters

One row with an outline for each file.

gdal raster index west.tif east.tif files.gpkg --overwrite

Two rectangles side by side, a wide one on the left and a narrow one on the right.

With thousands of satellite pictures, this is how you find the right ones.

N5: One band out of three

The map has red, green and blue. Take the blue one.

gdal raster select map.tif blue.tif --band 3 --overwrite

The blue part of the map in grey. The lake is the brightest area.

Satellite pictures have many bands, and most questions need two or three of them.

O: From raster to vector, and back

O1: Polygons from classes

Each group of equal cells becomes a shape.

gdal raster polygonize clean.tif clean.gpkg --attribute-name class --overwrite

The four classes as polygons with dark, stepped outlines.

If you look closely, the borders are small steps, because they follow the cells.

O2: Points from cells

Every cell becomes a point with its value.

gdal raster as-features tiny.tif dots.gpkg --geometry-type point --overwrite

Twelve dots in three rows of four.

tiny.tif has twelve cells. For west.tif there would be more than two million points.

O3: Cells from shapes, with a number from the table

Draw the contour lines of section 3, and give each cell the height of its line.

gdal vector rasterize lines.gpkg line_heights.tif --attribute-name height --size 1260,1710 --overwrite

Cells without a line are 0.

O4: Where are the towns close together?

Count the towns within 0.1 degrees of each cell.

gdal vector grid count towns.csv crowd.tif --oo X_POSSIBLE_NAMES=lon --oo Y_POSSIBLE_NAMES=lat --zfield lat --extent 98.3,2.15,99.4,3.1 --size 440,380 --radius 0.1 --overwrite

Grey discs around the towns. Where they overlap they are brighter, most of all at the east side of Samosir.

The --oo options tell GDAL which columns hold the position, so no point file is needed first.

O5: The mean height of each district

zonal-stats again, with another word.

gdal raster zonal-stats toba.tif /vsistdout/ --output-format CSV --zones districts.gpkg --include-field name --stat mean --stat min --stat max
name,mean,min,max
Asahan,512.262350082308,56,2185
Dairi,1355.86237781295,578,2445
Danau Toba,901.418828106173,901,1094
Deli Serdang,1249.24655376132,696,1708
Humbang Hasundutan,1127.04268554035,30,2032
Karo,1256.00168147511,640,2441
Kota Pematang Siantar,397.012914121095,247,584
Labuhan Batu Utara,1625.64835164835,1425,1891
Pakpak Bharat,1136.587087349,431,1827
Samosir,1400.47479666325,901,2145
Serdang Bedagai,436.892091529506,176,1232
Simalungun,719.653956512971,37,2083
Tapanuli Utara,1308.85386377144,901,2044
Toba Samosir,1166.96600464474,107,2280

As before, this is the part of each district that lies in our raster.

P: Two or three steps in one line

You know all commands in these lines from the cases before. Here they are combined with exclamation marks.

P1: Cut, then shade

The light on the northern end of the lake.

gdal raster pipeline read toba.tif ! clip --bbox 98.4,2.7,98.8,3.0 ! hillshade ! write north.tif --overwrite

The northern end of Lake Toba in grey relief, with steep walls on three sides.

Read, cut, shade, write.

P2: Smooth, then draw lines

Smooth contour lines in one line.

gdal pipeline read toba_utm.tif ! neighbors --kernel gaussian --size 5 ! contour --interval 200 --elevation-name height ! write calm.gpkg --overwrite

Smooth contour lines, one every 200 metres.

A raster goes in and a vector comes out. gdal pipeline, without the word raster, allows both.

P3: The flat land

Slope, then a class for everything below 5 degrees.

gdal raster pipeline read toba.tif ! slope ! reclassify -m "[0,5)=1; [5,91)=0" --ot Byte ! write flat.tif --overwrite

Flat land is white: the lake, large parts of the north-east and of the plateau in the west, and the plain at the south-eastern end of the lake.

The lake is flat, too, so it is in the same class. The slope does not show whether a cell is land or water.

P4: The lake without the district file

Take the cells of 901 m, remove the very small areas, make polygons, and keep the ones with the value 1. First 1 for the water and 0 for the rest:

gdal raster reclassify toba.tif toba_class.tif -m "901=1; DEFAULT=0" --ot Byte --overwrite

Then:

gdal pipeline read toba_class.tif ! sieve --size-threshold 5000 ! polygonize --attribute-name v ! filter --where "v=1" ! write found.gpkg --overwrite

The outline of Lake Toba with Samosir as an island, in small steps.

This polygon of the lake comes from the relief alone.

P5: Is it the same lake?

Compare its area with the one from section 6.

gdal vector sql found.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select round(sum(st_area(geom,1))/1e6) km2 from polygonize"
km2
1120

The districts gave 1,102 km2, and the encyclopaedia 1,130 km2.

P6: Colours and size in one go

From heights to a finished small picture.

gdal raster pipeline read toba.tif ! color-map --color-map toba.txt ! materialize ! resize --size 660,0 -r average ! write small_map.png --overwrite

The height colours of Lake Toba without shade: green lowlands, a blue lake and sand-coloured mountains.

materialize finishes the colours before the picture becomes smaller. Without it, GDAL would make the heights smaller first, and the cells at the shore would get a mean height that is not 901 m, and a wrong colour.

Q: Map projections

The Earth is round, and a map is flat. What is right on it, and what is wrong, depends on the projection. Here are the everyday cases. Chapter 2 explains projections in detail.

Q1: Which UTM zone does my place have?

A UTM zone is 6 degrees wide. The code is 326 and the number of the zone in the north of the equator, and 327 in the south.

gdal vector sql towns.csv /vsistdout/ --output-format CSV --dialect SQLite --sql "select name, 32600+cast((cast(lon as real)+186)/6 as integer) epsg from towns limit 3"
name,epsg
Ambarita,32647
Balige,32647
Dolok Sanggul,32647

EPSG:32647 is zone 47 north. That is why the maps of this chapter are in this one. For a place in the south, write 32700 in place of 32600.

Q2: Where is this place in metres?

One point, from degrees to UTM. This is Parapat, on the shore of the lake.

gdaltransform -output_xy -s_srs EPSG:4326 -t_srs EPSG:32647 -coord 98.9349 2.663
492763.768955082 294343.831178832

East and north, in metres. With -s_srs and -t_srs exchanged, it goes back.

Q3: How large is it, really?

The area of the lake and of some districts, measured in four ways.

gdal vector sql districts.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select name, round(st_area(geom,1)/1e6) on_the_earth, round(st_area(st_transform(geom,32647))/1e6) in_utm, round(st_area(st_transform(geom,3857))/1e6) on_a_web_map, round(st_area(geom),4) square_degrees from district where name in ('Danau Toba','Samosir','Dairi')"
name,on_the_earth,in_utm,on_a_web_map,square_degrees
Dairi,1993,1991,2011,0.1621
Danau Toba,1102,1102,1112,0.0897
Samosir,1238,1237,1249,0.1007

The first number is the true one, in square kilometres. UTM is very close. The web map is too large, here by 1 percent, and more the farther you go from the equator. The last one is an area in square degrees, and it has no useful meaning. If your areas are very small numbers, this is the probable cause.

Q4: How far is everything from here?

Put one place into the middle of a map. aeqd then has all distances from this middle right.

gdal raster reproject toba.tif here.tif --dst-crs "+proj=aeqd +lat_0=2.663 +lon_0=98.9349 +datum=WGS84" --bbox -25000,-25000,25000,25000 --resolution 100,100 -r average --overwrite

A square piece of the relief with Parapat in its middle. The lake runs through it from the upper left to the lower right.

The position of a cell is now its distance from Parapat, in metres to the east and to the north. Such maps are useful for a radio mast, an airport or an epicentre.

Q5: The world with Indonesia in the middle

sea360.tif has the temperature of all seas, in cells of one degree (ledger L96). lon_0 is the longitude in the middle.

gdal raster reproject sea360.tif world.tif --dst-crs "+proj=eqearth +lon_0=118 +datum=WGS84" --bbox -17243960,-8392928,17243960,8392928 --size 1200,584 -r bilinear --overwrite

A rounded map of the world with black land and grey seas. Indonesia is in the middle, the Pacific to the right, and South America is cut into two pieces at the edges.

This projection keeps all areas right. The box is the whole world in its metres. With polygons in place of a raster, such a map has errors where polygons cross its edge. Chapter 2 shows how to repair them.

Q6: An old datum moves a place by 168 m

The same two numbers are two different places if the datum is different. This is the National Monument in Jakarta, read from a map with the old datum Batavia.

gdaltransform -output_xy -s_srs EPSG:4211 -t_srs EPSG:4326 -coord 106.8272 -6.1754
106.828708492641 -6.17520793036197

The place is 0.0015 degrees farther east than the numbers say. If one of your layers is shifted by 50 to 300 m against the others, always in the same direction, the cause may be an old datum.

R: A scan without coordinates

Old maps are usually available as scanned pictures. scan.jpg is a piece of a real one, Indonesia 1:250,000 by the U. S. Army Map Service, found on Wikimedia Commons (ledger L117). It has no date, but it has the spelling Tandjung, which was used before 1972. Open it and look at the details. There are place names that have changed, and roads whose position is only approximate.

R1: Does this picture have coordinates?

gdal raster info shows this.

gdal raster info scan.jpg
Driver: JPEG/JPEG JFIF
Files: scan.jpg
Size is 2570, 2600
Image Structure Metadata:
  SOURCE_COLOR_SPACE=YCbCr
  INTERLEAVE=PIXEL
  COMPRESSION=JPEG
  JPEG_QUALITY=80
Corner Coordinates:
Upper Left  (    0.0,    0.0)
Lower Left  (    0.0, 2600.0)
Upper Right ( 2570.0,    0.0)
Lower Right ( 2570.0, 2600.0)
Center      ( 1285.0, 1300.0)
Band 1 Block=2570x1 Type=Byte, ColorInterp=Red
  Overviews: 1285x1300, 643x650, 322x325
  Image Structure Metadata:
    COMPRESSION=JPEG
Band 2 Block=2570x1 Type=Byte, ColorInterp=Green
  Overviews: 1285x1300, 643x650, 322x325
  Image Structure Metadata:
    COMPRESSION=JPEG
Band 3 Block=2570x1 Type=Byte, ColorInterp=Blue
  Overviews: 1285x1300, 643x650, 322x325
  Image Structure Metadata:
    COMPRESSION=JPEG

There is no coordinate system, and the corners are numbers of pixels. So GDAL cannot place this picture on a map.

R2: I know the corners

If a picture is not rotated and has no margin, its box is enough. As an example, here is our small map, copied without the small file that contains its coordinates:

gdal raster convert small_map.png corners.tif --config GDAL_PAM_ENABLED=NO --overwrite

Then:

gdal raster edit corners.tif --bbox 98.3,2.15,99.4,3.1 --crs EPSG:4326

The order is west, south, east, north. A scan of paper is rarely so simple.

R3: Which grid is printed on it?

The map has black lines every 10 km. At the upper edge, the blue numbers 262, 263 and 264 count them, so the first line lies 2,620,000 m east. UTM has no such numbers. Which systems exist for this place?

projinfo --list-crs projected --authority EPSG --bbox 98.3,2.15,99.4,3.1 --spatial-test intersects
EPSG:3001 "Batavia / NEIEZ"
EPSG:3375 "GDM2000 / Peninsula RSO"
EPSG:3395 "WGS 84 / World Mercator"
EPSG:3408 "NSIDC EASE-Grid North"
EPSG:3410 "NSIDC EASE-Grid Global"
EPSG:3832 "WGS 84 / PDC Mercator"
EPSG:3857 "WGS 84 / Pseudo-Mercator"
EPSG:4087 "WGS 84 / World Equidistant Cylindrical"
EPSG:5330 "Batavia (Jakarta) / NEIEZ"
EPSG:6931 "WGS 84 / NSIDC EASE-Grid 2.0 North"
EPSG:6933 "WGS 84 / NSIDC EASE-Grid 2.0 Global"
EPSG:8857 "WGS 84 / Equal Earth Greenwich"
EPSG:8858 "WGS 84 / Equal Earth Americas"
EPSG:8859 "WGS 84 / Equal Earth Asia-Pacific"
EPSG:9477 "SRGI2013 / UTM zone 47N"
EPSG:10594 "WGS 84 / GLANCE Asia"
EPSG:10601 "WGS 84 / GLANCE Oceania"
EPSG:23831 "DGN95 / Indonesia TM-3 zone 47.1"
EPSG:23832 "DGN95 / Indonesia TM-3 zone 47.2"
EPSG:23847 "ID74 / UTM zone 47N"
EPSG:23867 "DGN95 / UTM zone 47N"
EPSG:27703 "WGS 84 / Equi7 Asia"
EPSG:27706 "WGS 84 / Equi7 Oceania"
EPSG:32247 "WGS 72 / UTM zone 47N"
EPSG:32447 "WGS 72BE / UTM zone 47N"
EPSG:32600 "WGS 84 / UTM grid system (northern hemisphere)"
EPSG:32647 "WGS 84 / UTM zone 47N"

There are 27. Only two have the name of old Jakarta, and the first one is Batavia / NEIEZ, EPSG:3001. This is the Netherlands East Indies Equatorial Zone, the old Dutch grid. Its middle is 110 degrees east, and has the number 3,900,000.

R4: Is it this one?

The margin has a mark for 99 degrees east, a little to the left of line 268. Ask PROJ where this meridian is in the old grid:

gdaltransform -output_xy -s_srs EPSG:4211 -t_srs EPSG:3001 -coord 99 2.6
2679300.75839329 1186702.88912893

2,679,301, so 700 m to the left of 2,680,000. It is this one. The second number tells which lines run through the lake: 1,180,000 and 1,190,000 m north are the nearest.

R5: I know four points

Open the scan in any image program, and note the pixel of some crossings. Each --gcp has the column, the row, and then east and north. A JPEG file can not keep such notes, so make a GeoTIFF of it first:

gdal raster convert scan.jpg scan.tif --overwrite

Then:

gdal raster edit scan.tif --crs EPSG:3001 --gcp 29,343,2620000,1220000 --gcp 2488,338,2710000,1220000 --gcp 43,2528,2620000,1140000 --gcp 2504,2527,2710000,1140000

These are called ground control points. No pixel has moved yet. The file only contains the four points now.

R6: How good is it?

Test it with a crossing that you have not used. The one of the lines 2,670,000 and 1,180,000 is at pixel 1404, 1433.

gdaltransform -output_xy scan.tif -coord 1404 1433
2670089.6451942 1180014.38165132

It is 90 m too far east, and 14 m too far north. On a paper at 1:250,000, 90 m are a third of a millimetre, so this is very good. If your paper is bent, take more points, and add -tps here and in the next line. This option also corrects distortions inside the picture.

R7: Reproject it to the grid of the satellite image

Now the pixels move, from the old grid and the old datum to UTM and WGS 84. The box and the size are those of the satellite image.

gdalwarp -q -overwrite -t_srs EPSG:32647 -te 440000 255000 515000 322000 -ts 750 670 -r average scan.tif old_map.tif

The old map of Lake Toba in green, brown and light blue, with its black grid, now very slightly turned.

PROJ also converts the datum Batavia, because the definition of EPSG:3001 contains it.

R8: Old and new in one picture

The natural colours of 2021, and the old map over them with 60 percent.

gdal raster blend natural8.tif old_map.tif then_now.tif --opacity 60 --overwrite

The old map and the satellite image through each other. The shore of the lake is the same in both, and the old grid lies over the fields of today.

The shores of the two maps agree within about 100 m, although the old map was drawn by hand, on an ellipsoid of 1841. Chapter 14 continues with the question what has changed since then.

S: From points to a surface

Rain gauges, wells and drill holes are points, and you want a map. samples.csv has 80 random places with their height, read from our relief. So the true height of every cell is known, and we can measure the error of each method.

S1: The value of the nearest point

Each cell takes the value of the nearest point.

gdal vector grid nearest samples.csv guess_near.tif --oo X_POSSIBLE_NAMES=lon --oo Y_POSSIBLE_NAMES=lat --zfield height --extent 98.3,2.15,99.4,3.1 --size 440,380 --crs EPSG:4326 --overwrite

A mosaic of grey polygons with straight sides, one around each of the 80 places.

It uses only measured values, and it has steps that the land does not have. The polygons are called after Thiessen or Voronoi.

S2: Straight lines between the points

Triangles between the points, and a plane in each triangle.

gdal vector grid linear samples.csv guess_flat.tif --oo X_POSSIBLE_NAMES=lon --oo Y_POSSIBLE_NAMES=lat --zfield height --extent 98.3,2.15,99.4,3.1 --size 440,380 --crs EPSG:4326 --overwrite

A grey surface with sharp edges between flat triangles. Along the edges the steps of the nearest points are visible.

Outside of the outermost points there are no triangles, so the nearest point is used there.

S3: Near points count more

The mean of all points, where a point counts less the farther away it is.

gdal vector grid invdist samples.csv guess_smooth.tif --oo X_POSSIBLE_NAMES=lon --oo Y_POSSIBLE_NAMES=lat --zfield height --extent 98.3,2.15,99.4,3.1 --size 440,380 --crs EPSG:4326 --overwrite

A smooth grey surface with a bright or dark spot around each of the 80 places.

Inverse distance weighting, or IDW. The result is smooth. The round spots are typical for this method, and they do not exist on the land.

S4: Which one is best?

Compare each result with the true heights. First make the relief as coarse as the results. Then take the difference, without its sign:

gdal raster resize toba.tif truth.tif --size 440,380 -r average --overwrite

Then:

gdal raster calc -i A=guess_flat.tif -i T=truth.tif -o error.tif --calc "abs(A-T)" --overwrite

The size of the error in grey. It is dark near the 80 places and bright along the steep mountains between them.

The error is small around the points, and large where the land is steep and no point is near. How large is it on average?

S5: The mean error

One number for the whole map.

gdal raster zonal-stats error.tif /vsistdout/ --output-format CSV --zones footprint.geojson --stat mean --stat max
mean,max
139.110001598711,1474

139 m for the triangles. If you do the same with the other two, you get 170 m for the nearest point and 189 m for the smooth one. The smoothest map has the largest error here. Always leave out some points, and test the result with them. Chapter 15 shows how such an error affects a decision.

T: Two dates

before.tif is our place on 6 June 2018, and scene.tif is the same place on 3 October 2021 (ledger L95). What has changed in three years? The first file has only two bands, red and near infrared.

T1: How green was it then?

The NDVI again, as with scene.tif. Only the numbers of the bands are different.

gdal raster calc -i A=before.tif -o ndvi_2018.tif --flatten --calc "(A[2]-A[1])/(A[2]+A[1])" --propagate-nodata --nodata -9999 --overwrite

The greenness of 2018: pale land, a dark lake, and grey veils of cloud at the left and right edges.

Both images lie on the same grid. If yours do not, see the case about two rasters on the same grid.

T2: Two dates in one picture

Put the old date into red, and the new one into green and blue:

gdal raster stack ndvi_2018.tif ndvi.tif ndvi.tif two.tif --overwrite

Then:

gdal raster scale two.tif two_dates.tif --ot Byte --src-min 0 --src-max 1 --dst-min 0 --dst-max 255 --overwrite

Samosir and the land around the lake are pale grey. Red patches stand in the north-east and some small ones elsewhere, and light blue patches at the western and eastern edges.

Grey has not changed. Red was green in 2018 and is not any more. Light blue is greener than before. This method needs no threshold and no formula.

T3: New minus old

The difference as a number.

gdal raster calc -i A=ndvi_2018.tif -i B=ndvi.tif -o change.tif --calc "B-A" --propagate-nodata --overwrite

The difference in grey. Most land is of an even grey, with dark and bright patches in the north-east. The lake has large soft shapes.

The lake seems to have changed, too, but this is an error of the method. Water has almost no light in both bands, and the ratio of two tiny numbers is noise. So the next line leaves it out.

T4: Where did the plants disappear?

Three conditions in one formula: land in 2018, land in 2021, and a loss of more than 0.3.

gdal raster calc -i A=before.tif -i B=scene.tif -i C=change.tif -o lost.tif --calc "(A[2]>1000 && B[4]>1000 && C<-0.3) ? 1 : 0" --ot Byte --nodata 255 --overwrite

White patches on black. The largest ones stand at the eastern edge.

Near infrared below 1000 is water. A forest has much more.

T5: How many hectares is that?

Remove everything smaller than 20 cells, and make shapes of the rest:

gdal pipeline read lost.tif ! sieve --size-threshold 20 ! polygonize --attribute-name v ! filter --where "v=1" ! write lost.gpkg --overwrite

Then:

gdal vector sql lost.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select count(*) places, round(sum(st_area(geom))/1e4) hectares, round(max(st_area(geom))/1e4) largest from polygonize"
places,hectares,largest
56,5148,1335

The result is more than 5,000 hectares in three years. Check it before you use it: look at the largest area in the picture with the natural colours. It is a cloud.

T6: Without the clouds

Clouds are bright in blue, and land is dark. One more condition, and the same steps again:

gdal raster calc -i A=before.tif -i B=scene.tif -i C=change.tif -o lost2.tif --calc "(A[2]>1000 && B[4]>1000 && B[1]<700 && C<-0.3) ? 1 : 0" --ot Byte --nodata 255 --overwrite

gdal pipeline read lost2.tif ! sieve --size-threshold 20 ! polygonize --attribute-name v ! filter --where "v=1" ! write lost2.gpkg --overwrite

Then:

gdal vector sql lost2.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select count(*) places, round(sum(st_area(geom))/1e4) hectares, round(max(st_area(geom))/1e4) largest from polygonize"
places,hectares,largest
17,996,204

The result is 996 hectares. Four fifths of the first result were clouds. The rest is not certain either: a harvested field has the same values. Chapter 14 continues with this question.

U: Common problems with files

Each case starts with what you see, and shows the cause and the solution.

U1: My points are in the wrong ocean

Longitude and latitude were exchanged. Make such a file as an example:

gdal vector convert towns.csv wrong.gpkg --oo X_POSSIBLE_NAMES=lat --oo Y_POSSIBLE_NAMES=lon --overwrite

Then:

gdal vector swap-xy wrong.gpkg right.gpkg --overwrite

In wrong.gpkg, the towns have latitudes of 98 degrees. There is no such latitude, and this is how you recognise the mistake. Elsewhere it is harder to see: a point at 10, 50 and one at 50, 10 both exist.

U2: Commas in the numbers

messy.csv comes from a computer that writes 98,9349 and 1.029,5. Remove the point that groups the thousands, and turn the comma into a point.

gdal vector sql messy.csv /vsistdout/ --output-format CSV --dialect SQLite --sql "select name, cast(replace(east,',','.') as real) lon, cast(replace(north,',','.') as real) lat, cast(replace(replace(height,'.',''),',','.') as real) height from messy"
name,lon,lat,height
Parapat,98.9349,2.663,1029.5
Pangururan,98.6961,2.6081,912
Balige,99.0657,2.3328,933.5

GDAL has found the semicolons between the columns by itself. With a file name in place of /vsistdout/, you get a clean file.

U3: Degrees, minutes and seconds

minutes.csv has places like 02 39 47 N. A minute is a 60th of a degree, and a second is a 3600th. South is negative.

gdal vector sql minutes.csv /vsistdout/ --output-format CSV --dialect SQLite --sql "select name, substr(lon,1,3)+substr(lon,5,2)/60.0+substr(lon,8,2)/3600.0 lon, (substr(lat,1,2)+substr(lat,4,2)/60.0+substr(lat,7,2)/3600.0)*case when substr(lat,10)='S' then -1 else 1 end lat from minutes"
name,lon,lat
Parapat,98.935,2.66305555555556
Pangururan,98.6961111111111,2.60805555555556
Jakarta,106.827222222222,-6.17527777777778

substr(lat,4,2) is two letters from the fourth one on. Write 60.0 and not 60, or SQL divides whole numbers and drops the decimals.

U4: The layer has no coordinate system

QGIS asks for it, or the layer appears in the sea near Africa. If you are sure which system the numbers have, add it:

gdal vector edit right.gpkg named.gpkg --crs EPSG:4326 --overwrite

This changes no coordinate. It only writes the name of the system into the file. To change the coordinates, use reproject. It is a common mistake to use one in place of the other.

U5: The area of my field is 0

bow.geojson has a field whose corners are in the wrong order. Its border crosses itself. Repair it, and measure it:

gdal vector make-valid bow.geojson bow_ok.geojson --overwrite

Then:

gdal vector sql bow_ok.geojson /vsistdout/ --output-format CSV --dialect SQLite --sql "select name, round(st_area(geometry,1)/1e4) hectares from bow"
name,hectares
field,6149

Before the repair, the answer was 0, because one half was counted as positive and the other one as negative. make-valid makes two triangles of it. It does not restore the rectangle that was intended.

U6: A part of the shapefile is missing

A shapefile consists of several files, and people send you only some of them. If .shx is missing, GDAL can make a new one:

gdal vector convert old.shp old.gpkg --config SHAPE_RESTORE_SHX=YES --overwrite
Warning 1: Value of field 'name' is not a valid UTF-8 string.
..40...50...60..Warning 1: Value of field 'name' is not a valid UTF-8 string.
.70...80...90...100 - done.

The .shx is only a list of where each shape begins. Without .dbf you lose the table, and without .prj the name of the coordinate system. If .shp is missing, the shapes are lost and cannot be restored.

U7: The names are unreadable

The same file has names in Thai, and they appear as wrong characters. Text is stored as numbers, and this file uses another table of characters. For old Thai files, it is often number 874:

gdal vector convert old.shp thai.gpkg --oo ENCODING=CP874 --overwrite

Now they are Bangkok, Phuket and Hat Yai, in their own letters. For old files from western Europe try CP1252, for Chinese CP936, and for Russian CP1251.

U8: The minimum is -9999

A rain of minus ten metres is impossible. The number -9999 stands for “no data”, but the file has no note about this. Make such a file:

gdal raster convert march.tif minus.tif --overwrite

gdal raster edit minus.tif --nodata none

gdal raster info minus.tif --min-max
Driver: GTiff/GeoTIFF
Files: minus.tif
Size is 230, 260
Coordinate System is:
GEOGCRS["WGS 84",
    ENSEMBLE["World Geodetic System 1984 ensemble",
        MEMBER["World Geodetic System 1984 (Transit)"],
        MEMBER["World Geodetic System 1984 (G730)"],
        MEMBER["World Geodetic System 1984 (G873)"],
        MEMBER["World Geodetic System 1984 (G1150)"],
        MEMBER["World Geodetic System 1984 (G1674)"],
        MEMBER["World Geodetic System 1984 (G1762)"],
        MEMBER["World Geodetic System 1984 (G2139)"],
        MEMBER["World Geodetic System 1984 (G2296)"],
        ELLIPSOID["WGS 84",6378137,298.257223563,
            LENGTHUNIT["metre",1]],
        ENSEMBLEACCURACY[2.0]],
    PRIMEM["Greenwich",0,
        ANGLEUNIT["degree",0.0174532925199433]],
    CS[ellipsoidal,2],
        AXIS["geodetic latitude (Lat)",north,
            ORDER[1],
            ANGLEUNIT["degree",0.0174532925199433]],
        AXIS["geodetic longitude (Lon)",east,
            ORDER[2],
            ANGLEUNIT["degree",0.0174532925199433]],
    USAGE[
        SCOPE["Horizontal component of 3D system."],
        AREA["World."],
        BBOX[-90,-180,90,180]],
    ID["EPSG",4326]]
Data axis to CRS axis mapping: 2,1
Origin = (95.000000000000000,6.500000000000000)
Pixel Size = (0.050000000000000,-0.050000000000000)
Metadata:
  lat#standard_name=latitude
  lat#units=degrees_north
  lon#standard_name=longitude
  lon#units=degrees_east
  NC_GLOBAL#Conventions=CF-1.8
  NC_GLOBAL#source=Cut from CHIRPS v3.0, Climate Hazards Center, UC Santa Barbara
  NC_GLOBAL#title=Monthly rainfall over Sumatra, 2023
  NETCDF_DIM_EXTRA={time}
  NETCDF_DIM_time_DEF={12,4}
  NETCDF_DIM_time_VALUES={0,31,59,90,120,151,181,212,243,273,304,334}
  precip#long_name=rainfall of the month
  precip#units=mm
  precip#_FillValue=-9999
  time#calendar=standard
  time#standard_name=time
  time#units=days since 2023-01-01
  AREA_OR_POINT=Area
Image Structure Metadata:
  INTERLEAVE=BAND
Corner Coordinates:
Upper Left  (  95.0000000,   6.5000000) ( 95d 0' 0.00"E,  6d30' 0.00"N)
Lower Left  (  95.0000000,  -6.5000000) ( 95d 0' 0.00"E,  6d30' 0.00"S)
Upper Right ( 106.5000000,   6.5000000) (106d30' 0.00"E,  6d30' 0.00"N)
Lower Right ( 106.5000000,  -6.5000000) (106d30' 0.00"E,  6d30' 0.00"S)
Center      ( 100.7500000,   0.0000000) (100d45' 0.00"E,  0d 0' 0.00"N)
Band 1 Block=230x17 Type=Int16, ColorInterp=Gray
    Computed Min/Max=-9999.000,552.000
  Unit Type: mm
  Metadata:
    long_name=rainfall of the month
    NETCDF_DIM_time=59
    NETCDF_VARNAME=precip
    units=mm
    _FillValue=-9999

Then:

gdal raster edit minus.tif --nodata -9999

No cell has changed, but now all programs leave these cells out. Calculate the smallest and largest value again:

gdal raster info minus.tif --min-max
Driver: GTiff/GeoTIFF
Files: minus.tif
Size is 230, 260
Coordinate System is:
GEOGCRS["WGS 84",
    ENSEMBLE["World Geodetic System 1984 ensemble",
        MEMBER["World Geodetic System 1984 (Transit)"],
        MEMBER["World Geodetic System 1984 (G730)"],
        MEMBER["World Geodetic System 1984 (G873)"],
        MEMBER["World Geodetic System 1984 (G1150)"],
        MEMBER["World Geodetic System 1984 (G1674)"],
        MEMBER["World Geodetic System 1984 (G1762)"],
        MEMBER["World Geodetic System 1984 (G2139)"],
        MEMBER["World Geodetic System 1984 (G2296)"],
        ELLIPSOID["WGS 84",6378137,298.257223563,
            LENGTHUNIT["metre",1]],
        ENSEMBLEACCURACY[2.0]],
    PRIMEM["Greenwich",0,
        ANGLEUNIT["degree",0.0174532925199433]],
    CS[ellipsoidal,2],
        AXIS["geodetic latitude (Lat)",north,
            ORDER[1],
            ANGLEUNIT["degree",0.0174532925199433]],
        AXIS["geodetic longitude (Lon)",east,
            ORDER[2],
            ANGLEUNIT["degree",0.0174532925199433]],
    USAGE[
        SCOPE["Horizontal component of 3D system."],
        AREA["World."],
        BBOX[-90,-180,90,180]],
    ID["EPSG",4326]]
Data axis to CRS axis mapping: 2,1
Origin = (95.000000000000000,6.500000000000000)
Pixel Size = (0.050000000000000,-0.050000000000000)
Metadata:
  lat#standard_name=latitude
  lat#units=degrees_north
  lon#standard_name=longitude
  lon#units=degrees_east
  NC_GLOBAL#Conventions=CF-1.8
  NC_GLOBAL#source=Cut from CHIRPS v3.0, Climate Hazards Center, UC Santa Barbara
  NC_GLOBAL#title=Monthly rainfall over Sumatra, 2023
  NETCDF_DIM_EXTRA={time}
  NETCDF_DIM_time_DEF={12,4}
  NETCDF_DIM_time_VALUES={0,31,59,90,120,151,181,212,243,273,304,334}
  precip#long_name=rainfall of the month
  precip#units=mm
  precip#_FillValue=-9999
  time#calendar=standard
  time#standard_name=time
  time#units=days since 2023-01-01
  AREA_OR_POINT=Area
Image Structure Metadata:
  INTERLEAVE=BAND
Corner Coordinates:
Upper Left  (  95.0000000,   6.5000000) ( 95d 0' 0.00"E,  6d30' 0.00"N)
Lower Left  (  95.0000000,  -6.5000000) ( 95d 0' 0.00"E,  6d30' 0.00"S)
Upper Right ( 106.5000000,   6.5000000) (106d30' 0.00"E,  6d30' 0.00"N)
Lower Right ( 106.5000000,  -6.5000000) (106d30' 0.00"E,  6d30' 0.00"S)
Center      ( 100.7500000,   0.0000000) (100d45' 0.00"E,  0d 0' 0.00"N)
Band 1 Block=230x17 Type=Int16, ColorInterp=Gray
    Computed Min/Max=0.000,552.000
  NoData Value=-9999
  Unit Type: mm
  Metadata:
    long_name=rainfall of the month
    NETCDF_DIM_time=59
    NETCDF_VARNAME=precip
    units=mm
    _FillValue=-9999

U9: The map begins at Greenwich

Many global files run from 0 to 360 degrees, with America on the right. Ask for a box from -180 to 180.

gdal raster reproject sea360.tif sea180.tif --dst-crs EPSG:4326 --bbox -180,-90,180,90 --size 360,180 --overwrite

The usual map of the world in grey, with America on the left and Asia on the right. Land is black.

200 degrees east and 160 degrees west are the same place, and GDAL takes this into account. No value has changed, only the order.

V: The same for a whole folder

Often you do not have one file, but a hundred. Then the line goes into a loop. This is the one place where the shells differ, so there are three versions. Each makes a shaded picture of every file whose name ends with st.tif, which are west.tif and east.tif.

Windows, cmd:

for %f in (*st.tif) do gdal raster hillshade "%f" "%~nf_shade.png" --overwrite

Windows PowerShell and PowerShell 7:

Get-ChildItem *st.tif | ForEach-Object { gdal raster hillshade $_.Name "$($_.BaseName)_shade.png" --overwrite }

Linux, macOS and Git Bash:

for f in *st.tif; do gdal raster hillshade "$f" "${f%.tif}_shade.png" --overwrite; done

The line inside is always the same. Only the name of the variable for the file changes: %f, $_.Name or "$f". So test the line with one file first, and then put it into the loop. Chapter 16 is about large numbers of files.

Try it yourself

  • Evening light. Add --azimuth 270 to the first hillshade of section 3. Now the light comes from the west.
  • Your colours. Change the numbers in toba.txt, and run the last commands of section 5 again. What happens when the two blue rows say 1200?
  • Your distance. Make it 1 km in section 7, then 10 km. When does the hole in Samosir disappear?
  • Another district. Clip the map to Samosir: --like districts.gpkg --like-where "name='Samosir'".
  • A line of your own. Write a pipeline that reads west.tif, makes a hillshade and writes a PNG file. It has three steps.
  • The driest month. Take June from rain.tif and compare it with the mean, as in the case about March.
  • Your own data. Take a file from your work, and find five cases in the collection that fit it.

Checkpoint

The cell below stops with an error if the results are not what this chapter expects. It is written in Python, and you do not need to read it.

import csv
import io

def table(line):
    """The rows a line prints as CSV, as dictionaries."""
    return list(csv.DictReader(io.StringIO(oneline.run(line))))

area = {r["name"]: float(r["km2"]) for r in table('gdal vector sql districts.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select name, st_area(geom,1)/1e6 km2 from district"')}
assert abs(area["Danau Toba"] - 1130) < 40, "Lake Toba should have about 1,130 km2"

for a, b in (("map.tif", "whole.tif"), ("shade.tif", "old_shade.tif"), ("colour.tif", "old_colour.tif")):
    assert oneline.run(f"gdal raster compare {a} {b}") == "", f"{a} and {b} should be the same"

water = table("gdal raster pixel-info toba.tif 98.6 2.8 --position-crs EPSG:4326 --output-format CSV")[0]
assert water["band_1_raw_value"] == "901", "the water should lie at 901 m"

# Rain: the sum over the bands must be the sum of the twelve numbers at one place, and the two kinds of water must agree
months = [float(t) for t in oneline.run("gdallocationinfo -valonly -wgs84 rain.tif 98.95 2.65").split()]
year = float(oneline.run("gdallocationinfo -valonly -wgs84 year.tif 98.95 2.65"))
wet = float(oneline.run("gdallocationinfo -valonly -wgs84 wet_months.tif 98.95 2.65"))
assert len(months) == 12 and year == sum(months) and wet == sum(m > 200 for m in months), "the yearly rain should be the sum of the months"

found = float(table('gdal vector sql found.gpkg /vsistdout/ --output-format CSV --dialect SQLite --sql "select sum(st_area(geom,1))/1e6 km2 from polygonize"')[0]["km2"])
assert abs(found - 1130) < 40, "the lake found in the relief should have about 1,130 km2"

pictures = ("shade_west.png", "lines.png", "grey.png", "map.png", "around.png")
assert all((WORK / f).stat().st_size > 10_000 for f in pictures)
print(f"checkpoint passed: the lake lies at 901 m and has {area['Danau Toba']:,.0f} km2; one line and four commands made the same map; the rain of 2023 at the lake was {year:.0f} mm, with {wet:.0f} months above 200 mm")
print(f"time since the first cell: {time.perf_counter() - T0:.0f} s")
checkpoint passed: the lake lies at 901 m and has 1,102 km2; one line and four commands made the same map; the rain of 2023 at the lake was 2256 mm, with 5 months above 200 mm
time since the first cell: 336 s

Troubleshooting

Symptom Cause Fix
'gdal' is not recognized, command not found The environment is not active in this terminal conda activate gdal-oneliners
No such file or directory The terminal is in another folder than the files cd to the folder. dir or ls shows what is there
already exists The output is there from the last time Add --overwrite, or choose another name
The picture is empty, or its ground is missing 0 is marked as “no data” and becomes transparent gdal raster edit a.tif --nodata none before convert
The picture is white or black The numbers do not fit into a picture gdal raster scale ... --ot Byte, or a colour file as in section 5
The sea has -119,988 mm of rain “No data” was treated as a number --propagate-nodata in calc
Input extents are inconsistent Two rasters with different grids gdal raster reproject with the box and the size of the other one
The map is upside down, or lies at 0, 0 The netCDF or HDF5 file has no coordinates The cases about HDF5 in the collection
A distance of 5000 covers the whole world The layer is in degrees reproject to a system in metres first
Strange errors in Git Bash on Windows Git Bash changes words that start with a slash, such as /vsistdout/ Run export MSYS_NO_PATHCONV=1 once in each terminal. Chapter 1, section 5, explains it

What comes next

You now know the basic commands. The following chapters use them for larger questions. They are in seven parts, and each chapter continues with a question that the one before has left open: where is a place, where does something move, to whom does an area belong, how high is it, what has changed, what does it mean for people, and how can the work be repeated and shared?

The lines get longer, but you can divide every one of them into steps. Each chapter begins with a warm-up, a few short commands on its own data.

Chapter 1: The other side of the Earth reads its data from the web, and uses SQL to calculate the places that lie exactly opposite Indonesia.

Relief: Copernicus DEM GLO-30, produced using Copernicus WorldDEM-30 © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved. Districts: BPS through OCHA, CC BY-IGO. Towns: GeoNames, CC BY 4.0. Image: contains modified Copernicus Sentinel data 2021. Rain: CHIRPS3, Climate Hazards Center, UC Santa Barbara, CC BY 4.0. Sea: CoralTemp v3.1, NOAA Coral Reef Watch.