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:
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 sysimport timefrom pathlib import Path# The repository root, whether the notebook runs from en/, id/ or the root itselfROOT = Path.cwd() if (Path.cwd() /"tutorial.yml").exists() else Path.cwd().parentsys.path.insert(0, str(ROOT /"src"))import onelineT0 = time.perf_counter()WORK = oneline.start("00") # a folder outside the repository; see src/oneline.py to choose itprint("working folder:", WORK.name, "| files copied there:", sorted(f.name for f in (ROOT /"sample-data/ch00").iterdir()))
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:
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?
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:
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:
Warning 6: PNG driver doesn't support data type Int16. Only eight bit (Byte) and sixteen bit (UInt16) bands supported. Defaulting to Byte
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:
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:
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:
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:
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:
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:
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.
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:
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
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.
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.
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"
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.
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 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 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.
&& 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.
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.
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.
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.
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
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.
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.
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.
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:
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.
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.
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.
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.
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.
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"
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"
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"
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.
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.
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.
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:
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?
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:
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:
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.
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.
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.
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 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 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:
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"
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"
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:
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:
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:
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:
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
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 csvimport iodef table(line):"""The rows a line prints as CSV, as dictionaries."""returnlist(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"')}assertabs(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 agreemonths = [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"))assertlen(months) ==12and year ==sum(months) and wet ==sum(m >200for 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"])assertabs(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")assertall((WORK / f).stat().st_size >10_000for 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.