Skip to main content

Chapter 14: An old map and satellite images compared

Chapter 14: An old map and satellite images compared

TipAt a glance
  • In this series: Part V, Then and now. Chapter 13 was about the average year. This chapter compares the same place at different times, and looks for the changes
  • You will build: An old Army map with its position on Earth; its lake drawn over the lake of today; one year of satellite images on one sheet; a map of the years in which trees were cut; and twelve images of a canal that was made wider
  • You need: Chapter 0, for the environment, and section 5 of Chapter 1, for lines that work in every shell. Chapter 8 explains the SQL queries on a raster
  • Time to run: The commands took about four minutes when tested, including about 150 MB of downloads, or much less with the copies in the folder. About 300 MB of free space
  • Level: Intermediate; the second half of section 1, and section 3, have longer queries

This chapter compares the same place at two times, and looks for the differences.

There are three common problems. The two pictures may not have the same position. Something may cover the ground, and in Indonesia this is nearly always a cloud. Or the difference is real, but it comes from the season and is not a permanent change.

The place is Lake Toba again, as in Chapter 0. There is an old map of it by the U. S. Army, and there are satellites that photograph it every few days. This chapter uses both.

NoteLearning objectives

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

  • give an old map its position on Earth, and test how accurate this position is;
  • compare a shore on paper with a shore of today, in metres;
  • search an archive of satellite images with one line;
  • show many images on one sheet, without downloading them;
  • make a map without clouds from many cloudy days;
  • find the year in which something changed;
  • show two times in one picture.

Before running this chapter, do section 1 of Chapter 0 and section 5 of Chapter 1. In a terminal, make a new empty folder and copy into it the files of sample-data/ch14. In this notebook, the next cell does that.

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("14")
print("working folder:", WORK.name, "| files copied there:", sorted(f.name for f in (ROOT / "sample-data/ch14").iterdir()))
working folder: ch14 | files copied there: ['crossings.csv', 'days.csv', 'nbr.txt', 'offline_days.tif', 'offline_relief.tif', 'offline_strip.tif', 'offline_visits.csv', 'shore.txt', 'toba_map.jpg', 'today.tif', 'years.tif', 'years.txt']

Warm-up

Two files are in the folder. toba_map.jpg is a scan of the old map. today.tif is the lake in natural colours, from satellite images of 2026. Cut the same place out of both, the town of Pangururan:

gdal raster clip toba_map.jpg then.png --window 1400,1050,440,440 --overwrite

gdal raster clip today.tif now.png --bbox 458000,280500,474000,296500 --overwrite

A piece of the old map, with a thick black road along the western shore of Samosir. At Pangururan, the island nearly touches the mainland, and a road crosses to it. Many small yellow squares with names of villages, brown hills in the west.

The same area in the satellite image: dark water in the north and in the south, green hills in the west, pale fields in the east, and a thin dark line of water between them at Pangururan.

Look before moving on. Find Pangururan in both, and the bay to the north of it. Is it the same land? Compare the shores.

Then look at the two commands. The first one cuts with columns and lines of a picture (--window), and the second one with metres on the Earth (--bbox). For GDAL, the scan of the old map is only a picture, because the file has no coordinates. The window of the first command was found by trial.

So GDAL has no information that the two belong to the same place. Adding this information is the first task.

1. Give the old map its position

The map is Indonesia 1:250,000 by the U. S. Army Map Service, joined from two sheets, from Wikimedia Commons (ledger L117). No date is given there. It writes Tandjung, the spelling that was used before 1972, and the catalogue of a library in Hawaii seems to have first editions of these two sheets from 1954 and 1955 (ledger L131). So this chapter calls it “the old map”, and assumes that it is from the 1950s.

In Chapter 0, you gave a small piece of this map its position, with four points. The black grid on the paper has lines every 10 km, and where two lines cross, the coordinates are known. The whole map has 140 such crossings. crossings.csv has 137 of them:

ogr2ogr -overwrite cross.gpkg crossings.csv -oo AUTODETECT_TYPE=YES -nln cross

ogr2ogr -f CSV /vsistdout/ cross.gpkg -sql "select * from cross limit 3"
id,column,line,x,y
1,381.5,2843.9,2600000,1130000
2,379.2,2570.7,2600000,1140000
3,377,2298.8,2600000,1150000

column and line are the place in the picture. x and y are the place on the Earth, in the coordinates of the map (EPSG:3001). A small script found the crossings. You can also mark them by hand in QGIS, in about an afternoon. (For the other three, the result of the script was not certain, so they are not in the file.)

Give all of them to the picture, and transform it into the coordinates of today:

gdal raster convert toba_map.jpg map.tif --overwrite

gdal raster edit map.tif --crs EPSG:3001 --gcp "@crossings.csv"

gdalwarp -q -overwrite -tps -t_srs EPSG:32647 -te 409000 232000 552000 332000 -tr 80 80 -r average map.tif sheet.tif
Part What it does
convert makes a GeoTIFF. It can store control points, and a JPEG can not
--gcp "@crossings.csv" reads the ground control points from a file with the columns column, line, x and y. Without the @, you write them one by one. The quotes are for PowerShell, where @ has a special meaning
-tps a thin plate spline: the map is bent smoothly, so that every control point is exactly in its place. Without it, gdalwarp uses one formula for the whole map
-t_srs EPSG:32647 from the Batavia datum of the map to WGS 84, in metres

How accurate is the position?

This question is often forgotten. gdalwarp gives no error message when the points are wrong. It transforms the picture with wrong points in the same way as with right ones.

A fair test does not use all the points for the transformation. Fit the map with every second crossing only, and then check where the other crossings are placed. SpatiaLite has two functions for this, gcp_compute and gcp_transform. The query is long, but it tests four methods at once:

ogr2ogr -f CSV /vsistdout/ cross.gpkg -dialect SQLite -sql "select how, round(sqrt(avg(case when id-2*(id/2)=0 then d*d end)),1) used_m, round(sqrt(avg(case when id-2*(id/2)=1 then d*d end)),1) kept_back_m, round(max(d),1) worst_m from (select how, k, id, st_distance(gcp_transform(makepoint([column],line),m),makepoint(x,y)) d from cross, (select how, k, gcp_compute(makepoint([column],line),makepoint(x,y),k) m from cross, (select 1 k, 'flat' how union select 2, 'curved' union select 3, 'curved twice' union select 0, 'rubber') where id-2*(id/2)=0 group by k)) group by k order by kept_back_m desc"
how,used_m,kept_back_m,worst_m
flat,50.7,53.5,174.1
curved,40.2,49.1,165.3
curved twice,30.5,38.7,94.8
rubber,0,32.2,97.2
Part What it does
gcp_compute(a,b,k) takes all pairs of points and calculates one transformation. k is the method: 1 is flat (shift, turn, stretch), 2 and 3 bend the map more and more, and 0 is the thin plate spline, here called “rubber”
gcp_transform(a,m) applies the transformation m to one point
id-2*(id/2) is 0 for even numbers and 1 for odd ones, because a whole number divided by 2 loses its remainder. The usual sign for this has another meaning in the command window of Windows
used_m, kept_back_m the typical error in metres, at the points that were used for the transformation, and at the points that were not used

Compare the two columns. The thin plate spline has an error of 0 at its own points, because the method places them exactly. So this number says nothing about the accuracy. At the points that were kept back, the error is 32 m, and this is still the best of the four. One dot of the scan is 37 m wide.

So the position of the map is accurate to about one dot, at least on its own grid. And what is wrong with the flat transformation? Draw its errors, 80 times too large:

gdal raster calc -i A=sheet.tif -o darts.tif --calc "A*0.35+165" --ot Byte --overwrite

ogr2ogr -overwrite darts.gpkg cross.gpkg -dialect SQLite -sql "select st_transform(setsrid(st_convexhull(st_collect(st_buffer(makepoint(x,y),600),makepoint(x+80*(st_x(g)-x),y+80*(st_y(g)-y)))),3001),32647) geom from (select x, y, gcp_transform(makepoint([column],line),m) g from cross, (select gcp_compute(makepoint([column],line),makepoint(x,y),1) m from cross))" -nln dart -nlt POLYGON -a_srs EPSG:32647

gdal_rasterize -q -b 1 -b 2 -b 3 -burn 190 -burn 60 -burn 30 -l dart darts.gpkg darts.tif

gdal raster resize darts.tif darts.jpg --size 1430,1000 -r average --overwrite --co QUALITY=85

The whole old map of Lake Toba in pale colours, with a red pointed shape at every crossing of the grid. Neighbouring shapes point in nearly the same direction: to the south-west in the north, to the north-west in the middle, to the north-east at the right edge.

The thick end of each red shape is at the true place of the crossing, and the tip points to the place where the flat transformation puts it. Each shape is the convex hull of a circle and a point (st_convexhull).

Look before moving on. If these errors were random, the shapes would point in all directions. They do not. Neighbours mostly point in the same direction, and the direction changes slowly over the map. So the paper is bent smoothly. Possible causes are its age, the folds, the scanner, or the joining of the two sheets. This is why the thin plate spline works here. It can correct errors that change smoothly. It can not correct random errors.

2. Is the shore in the right place?

Now the map is accurate on its own grid. But is the land on the map in the right place? The grid was printed by a machine. The shore was measured by people.

The test needs one object that is in both data sets, and a lake is suitable. On the map, it is blue. In an elevation model, it is flat. First put both into the same cells, 40 m wide:

gdalwarp -q -overwrite -tps -t_srs EPSG:32647 -te 436000 252000 520000 324000 -tr 40 40 -r average map.tif old.tif

gdalwarp -q -overwrite -t_srs EPSG:32647 -te 436000 252000 520000 324000 -tr 40 40 -r bilinear /vsicurl/https://copernicus-dem-30m.s3.amazonaws.com/Copernicus_DSM_COG_10_N02_00_E098_00_DEM/Copernicus_DSM_COG_10_N02_00_E098_00_DEM.tif /vsicurl/https://copernicus-dem-30m.s3.amazonaws.com/Copernicus_DSM_COG_10_N02_00_E099_00_DEM/Copernicus_DSM_COG_10_N02_00_E099_00_DEM.tif relief.tif

The relief is the Copernicus model again (ledger L80). “Now” means the years 2010 to 2014 in this section, because its satellites measured the land in these years. Without a connection, use offline_relief.tif as relief.tif.

Find the old lake and the new lake, and make polygons of them:

gdal pipeline calc -i A=old.tif --calc "(A[3]>A[1]+25 && A[3]>140 && A[3]+3>A[2]) ? 1 : 0" --flatten --ot Byte --nodata 0 ! sieve --size-threshold 8 ! polygonize ! write blue.gpkg --overwrite --output-layer blue

gdal pipeline calc -i D=relief.tif --calc "(abs(D-901)<=2) ? 1 : 0" --ot Byte --nodata 0 ! polygonize ! write flat.gpkg --overwrite --output-layer flat

ogr2ogr -overwrite shore.gpkg blue.gpkg -dialect SQLite -sql "select 1 code, st_buffer(st_union(st_buffer(geom,200)),-200) geom from blue" -nln lake -nlt POLYGON -explodecollections

ogr2ogr -update -append shore.gpkg flat.gpkg -dialect SQLite -sql "select 2 code, geom from flat order by st_area(geom) desc limit 1" -nln lake

ogr2ogr -overwrite lakes.gpkg shore.gpkg -dialect SQLite -sql "select code, st_buffer(geom,0) geom from lake where st_area(geom)>1e9" -nln lake
Line What it does
1 a cell is blue when its blue (band 3) is clearly above its red (band 1), and not below its green (band 2). sieve removes small spots
2 in this model, the lake is flat, at 901 m
3 letters and grid lines are printed over the water, and they cut it into pieces. Every piece grows by 200 m, the pieces are joined, and the result shrinks by 200 m again. Then most lines are gone, and the shore is in its old place again
4 and 5 both lakes in one layer, the old one with code 1 and the new one with code 2. Only lakes of more than 1,000 km2 are kept

Draw them over each other. gdal_rasterize -add adds the codes: 1 is water only on the old map, 2 is water only in the new data, and 3 is water in both:

gdal_rasterize -q -add -a code -l lake -init 0 -ot Byte -te 436000 252000 520000 324000 -tr 40 40 lakes.gpkg both.tif

gdal raster hillshade relief.tif shade.tif -z 2 --overwrite

gdal raster pipeline calc -i B=both.tif -i S=shade.tif --calc "B*60+S/4.5" --ot Byte ! color-map --color-map shore.txt ! materialize ! resize --size 1400,1200 -r average ! write shore.jpg --overwrite --co QUALITY=90

Lake Toba in pale blue, on a pale grey relief of the land. Thin red and dark blue strips follow parts of the shore. The red ones are widest along the north-west of Samosir and at the south-eastern end of the lake. In the open water are a few dark blue dots.

Look before moving on. Pale blue is water on the old map and in the elevation model. Red is water only on the old map, and dark blue is water only in the new data. The red and blue strips are so thin that they are hard to find.

The dark blue dots in the open water are not islands that have disappeared. They are parts of the words Danau Toba, because the 200 m were not enough for them. And look at Pangururan, at the narrowest place in the west of Samosir. A red strip joins the two halves of the lake there. Was there water on the old map? Section 6 answers this question.

In numbers, how much of the old shore lies within 50, 100, 200 and 400 m of the new one?

gdal raster zonal-stats both.tif share.csv --zones both.tif --stat count --overwrite

ogr2ogr -f CSV /vsistdout/ share.csv -dialect SQLite -oo AUTODETECT_TYPE=YES -sql "select case value when 1 then 'water only then' when 2 then 'water only now' else 'water then and now' end what, round(count*0.0016,1) km2 from share where value>0"

ogr2ogr -f CSV /vsistdout/ lakes.gpkg -dialect SQLite -sql "select m within_m, cast(round(100*st_length(st_intersection(o.g,st_buffer(n.g,m)))/st_length(o.g)) as integer) percent_of_the_old_shore from (select st_exteriorring(geom) g from lake where code=1) o, (select st_exteriorring(geom) g from lake where code=2) n, (select 50 m union select 100 union select 200 union select 400) order by m"
what,km2
water only then,24.5
water only now,15.3
water then and now,1114.2
within_m,percent_of_the_old_shore
50,48
100,75
200,92
400,98

Three quarters of the old shore lie within 100 m of the new one. On the paper, 100 m are 0.4 millimetres. And this number includes all the errors of all the steps: the survey, the drawing, the printing, the paper, the scan, the 137 points, and the change from one datum to another. This is an accurate map.

Where is it red? Mostly at flat shores, where the land slopes very gently into the water: along the north-west of Samosir, and around Porsea in the south-east. There, if the lake falls by a metre, a wide strip of land becomes dry, wide enough to appear on a map. And the lake did fall. A study of the water level gives 905.2 m as the mean of the years 1957 to 1983, and 904.1 m for 1984 to 2020 (ledger L132). This does not prove that it is the cause of the red strips. But the place and the direction of the change agree with it.

3. How many images have few clouds?

The next data are satellite images. The Sentinel-2 satellites photograph the land of the Earth again and again, with cells of 10 m, and everybody may use the images (ledger L95). The difficult part is to choose the right image.

There is an archive with a search on the internet. Its answer is a list of images in GeoJSON. So for ogr2ogr, it is a table like any other:

ogr2ogr -f CSV -overwrite visits.csv "https://earth-search.aws.element84.com/v1/search?collections=sentinel-2-l2a&bbox=98.6,2.3,98.65,2.35&limit=250&datetime=2026-01-01T00:00:00Z/2026-12-01T23:59:59Z" -oo FLATTEN_NESTED_ATTRIBUTES=YES -dialect SQLite -sql "select substr(id,11,8) day, min([eo:cloud_cover]) cloud, replace([assets.visual.href],'TCI.tif','') folder from OGRGeoJSON where [s2:processing_baseline]<'04' or [earthsearch:boa_offset_applied]=1 group by day order by cloud"

ogr2ogr -f CSV /vsistdout/ visits.csv -dialect SQLite -oo AUTODETECT_TYPE=YES -sql "select count(*) visits, sum(cloud<10) below_10, sum(cloud between 10 and 30) from_10_to_30, sum(cloud>30 and cloud<=80) from_30_to_80, sum(cloud>80) above_80 from visits"

ogr2ogr -f CSV /vsistdout/ visits.csv -dialect SQLite -oo AUTODETECT_TYPE=YES -sql "select day, cast(cloud as integer) cloud from visits limit 3"
visits,below_10,from_10_to_30,from_30_to_80,above_80
81,0,9,33,39
day,cloud
20260709,11
20260828,15
20260525,17
Part What it does
https://earth-search.../search? the search of the archive. bbox is a small box in degrees, and datetime has the first and the last day. All images that touch the box are in the answer. The box lies in the middle of one tile of the satellite, so there is one image for each day on which the satellite passes
FLATTEN_NESTED_ATTRIBUTES the answer has lists within lists. This makes columns of them, with a dot in the name
[eo:cloud_cover] the clouds in percent, for the whole image of 110 km. Names with a colon or a dot need brackets
replace(...) the folder of the image. All its files are there: TCI.tif has natural colours, B08.tif the near infrared, and so on
where ... avoids an error that is explained below

Without a connection, use offline_visits.csv as visits.csv.

A change in the numbers. On 25 January 2022, the meaning of the numbers in these files changed. Since the processing with the number 04.00, 1,000 is added to every value (ledger L133). This archive subtracts the 1,000 again, but not in all of its files. If you compare an image of 2021 with one of 2022, you may find a change that comes only from the processing. The where keeps the older images, and the images whose description states that the 1,000 is subtracted.

An example: in the image of 20 February 2022, one of the clearest of that year, the open water of the lake has 1,118 in B12. On 28 August 2026, it has 123.

There are 81 images in 335 days, so one every four days. Nearly half of them have more than 80 percent clouds. And not one has less than 10.

The next step shows all of them in one picture. It needs only two lines:

ogr2ogr -overwrite sheet.gpkg visits.csv -dialect SQLite -sql "select 'vrt:///vsicurl/'||folder||'TCI.tif?projwin=454000,290000,474000,270000&outsize=100,100&a_ullr='||x||','||y||','||(x+100)||','||(y-100) location, buildmbr(x,y-100,x+100,y) geom from (select folder, 104*(cast(substr(day,5,2) as integer)-1) x, -104*(row_number() over (partition by substr(day,5,2) order by day)-1) y from visits)" -nln sheet -nlt POLYGON -a_srs EPSG:32647

gdal raster select GTI:sheet.gpkg sheet.jpg --band 1,2,3 --overwrite --config GDAL_DISABLE_READDIR_ON_OPEN=EMPTY_DIR --co QUALITY=90

A sheet with twelve columns and up to eight small square pictures in each. Most of them are white or full of white clouds. In about ten of them, a dark arm of the lake between green hills can be seen clearly.

Every column is a month of 2026, from January to the first of December. In a column, the days go down. Each small square shows the same 20 km, with the western arm of the lake.

Look before moving on. Count the squares in which you can see the whole land. There are about ten. This is the number of clear images in one year at this place. A clear satellite image of such a place was selected from many cloudy ones.

How did this work? It uses two methods that are also useful for many other tasks:

Method What it means
vrt://FILE?... a file name can contain instructions. projwin cuts a window, outsize makes it 100 by 100 cells, and a_ullr gives the position of the result. Here, this is a place on an empty sheet. The image itself stays on the server, and GDAL reads only the parts that it needs
GTI:sheet.gpkg a table with a column location and a box for each row is one raster for GDAL (a tile index). The file of a row is opened when its place is drawn

So a query writes 81 names with instructions and 81 places, and select draws the sheet, in red, green and blue. The file is a JPEG, because photographs are much smaller in this format. JPEG has no transparency, so the empty places are black. The last part of the line, GDAL_DISABLE_READDIR_ON_OPEN, stops GDAL from looking for other files beside each image. Here, it saves a lot of time.

4. A map without clouds

No day is completely clear. But nearly every cell is clear on some day. So do not look for the best image. Take the nine best images, remove the clouds in each of them, and calculate the median of the clear values for every cell.

In place of natural colours, this section uses two bands that contain more information about plants. Leaves reflect a lot of near infrared light (B08) and little of the short-wave infrared (B12). For bare or burnt ground, it is the opposite. The two bands together give the normalized burn ratio. It was made for fires, and it shows harvests as well (ledger L134): (B08 - B12) / (B08 + B12). Here it is times 100. In this landscape, a dense forest has about 60, and bare soil 15 or less.

The third file, SCL, has a class for each cell. 4 to 7 are plants, bare soil, water and “unclassified”. Shadows and clouds have other numbers (ledger L133).

gdal vector sql visits.csv nir.csv --overwrite --lco HEADER=NO --dialect SQLite --sql "select '/vsicurl/'||folder||'B08.tif' from visits limit 9"

gdal vector sql visits.csv swir.csv --overwrite --lco HEADER=NO --dialect SQLite --sql "select '/vsicurl/'||folder||'B12.tif' from visits limit 9"

gdal vector sql visits.csv class.csv --overwrite --lco HEADER=NO --dialect SQLite --sql "select '/vsicurl/'||folder||'SCL.tif' from visits limit 9"

gdal raster stack "@nir.csv" nir.tif --resolution 40,40 --bbox 454000,270000,474000,290000 --overwrite --config GDAL_DISABLE_READDIR_ON_OPEN=EMPTY_DIR

gdal raster stack "@swir.csv" swir.tif --resolution 40,40 --bbox 454000,270000,474000,290000 --overwrite --config GDAL_DISABLE_READDIR_ON_OPEN=EMPTY_DIR

gdal raster stack "@class.csv" class.tif --resolution 40,40 --bbox 454000,270000,474000,290000 --overwrite --config GDAL_DISABLE_READDIR_ON_OPEN=EMPTY_DIR

Three lists with nine names each, and three stacks: nine days become nine bands. "@nir.csv" means that the names of the files are in this file, one per line. Now the two lines that remove the clouds:

gdal raster calc -i N=nir.tif -i S=swir.tif -i C=class.tif -o days.tif --calc "(C>=4 && C<=7) ? 100*(N-S)/(N+S) : -128" --ot Int8 --nodata -128 --overwrite

gdal raster calc -i A=days.tif -o clear.tif --dialect builtin --calc median --flatten --ot Int8 --overwrite
Part What it does
-i N= -i S= -i C= three files with nine bands each. calc takes the first band of all three, then the second, and so on. So this is one line for nine days
... : -128 with --nodata -128 a cloud becomes “no data”
--dialect builtin --calc median the value in the middle of the nine days. Cells with no data are not counted
--flatten from nine bands to one

Why the median, and not the mean? Because the mask misses some clouds. One wrong value among seven changes the mean a lot, and the median only a little.

Without a connection, use offline_days.tif as days.tif, and begin with the second of these two lines.

Show the nine days beside the result. It is the method of section 3 again, with a local file:

gdal raster stack days.tif clear.tif ten.tif --overwrite

ogr2ogr -overwrite nine.gpkg visits.csv -dialect SQLite -sql "select 'vrt://ten.tif?bands='||k||'&outsize=288,288&r=average&a_ullr='||x||','||y||','||(x+288)||','||(y-288) location, buildmbr(x,y-288,x+288,y) geom from (select rowid k, 297*(rowid-1-3*((rowid-1)/3)) x, -297*((rowid-1)/3) y from visits limit 9) union all select 'vrt://ten.tif?bands=10&outsize=882,882&r=cubic&a_ullr=909,0,1791,-882', buildmbr(909,-882,1791,0)" -nln nine -nlt POLYGON -a_srs EPSG:32647

gdal raster pipeline read GTI:nine.gpkg ! color-map --color-map nbr.txt ! write nine.jpg --overwrite --co QUALITY=90

Nine small maps at the left, with white holes of many shapes where the clouds were. At the right, one large map without holes: dark green forest in the south, green and yellow fields on the slopes, and brown strips of bare soil at the lower edge.

Look before moving on. There are nine maps with holes, and one map without holes. Dark green is dense forest, yellow is thinner, and brown is bare. At the lower edge, there are brown parallel strips between the green. Section 5 explains them.

(The colours in the lake have no meaning. Water reflects so little in both bands that their ratio is only noise.)

5. What has changed, and since when?

years.tif is the result of the same method, nine times. It has nine bands, one for each year from 2018 to 2026, and each is the median of the clear cells on the 15 clearest days of its year. It shows a larger area, with the hills in the west of the lake. It takes a long time to make, so it is already in the folder.

When trees are cut, the value falls from one year to the next, here typically from 60 to 20. So subtract each year from the year before it. With two stacks that are shifted by one band, this is one line:

gdal raster select years.tif before.tif --band 1,2,3,4,5,6,7,8 --overwrite

gdal raster select years.tif after.tif --band 2,3,4,5,6,7,8,9 --overwrite

gdal raster calc -i A=before.tif -i B=after.tif -o drop.tif --calc "(A>35) ? A-B : 0" --ot Int16 --nodata none --overwrite

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

gdal raster calc -i A=drop.tif -o when.tif --dialect builtin --calc argmax --flatten --overwrite

gdal raster clip both.tif water.tif --bbox 440000,256000,474000,290000 --overwrite

gdal raster calc -i M=most.tif -i W=when.tif -i L=water.tif -o year.tif --calc "(M>=20 && L<2) ? 2018+W : 0" --ot UInt16 --nodata none --overwrite
Part What it does
(A>35) ? A-B : 0 a cell is only used if it was green before. drop.tif has eight bands, from “2018 to 2019” to “2025 to 2026”
max the largest fall of the eight
argmax the number of the band with the largest fall. So this is the year: band 1 means 2019
M>=20 the limit for a clear fall, chosen for this chapter. Try others
L<2 not in the lake, which is in both.tif of section 2

max gives the size of the change, and argmax gives the time. These two work for all data with one band for each time: the wettest month, the hottest hour, the year with the highest price.

Now the map. The years get colours, and the land without a change stays grey, with the values of the last year:

gdal raster select years.tif last.tif --band 9 --overwrite

gdal raster pipeline calc -i Y=year.tif -i N=last.tif -i L=water.tif --calc "(L>=2) ? 111 : ((Y>0) ? Y-2018 : 11+max(0,N))" --ot Byte --nodata none ! color-map --color-map years.txt ! materialize ! write years.png --overwrite

gdal raster zonal-stats year.tif year.csv --zones year.tif --stat count --overwrite

ogr2ogr -overwrite bars.gpkg year.csv -oo AUTODETECT_TYPE=YES -dialect SQLite -sql "select value-2018 v, buildmbr(106*(value-2019)+3,0,106*(value-2019)+105,count*0.16/60) geom from year where value>0" -nln bars -nlt POLYGON -a_srs EPSG:32647

gdal pipeline read bars.gpkg ! rasterize --attribute-name v --init 0 --ot Byte --size 848,160 --extent 0,0,848,160 ! color-map --color-map years.txt ! write bars.png --overwrite

A dark grey map with many colours in the middle: hundreds of long narrow strips in blue, teal, pale green, yellow, orange and brown, each with the colour of one year. Beside them lies one large orange area. Around the black lake in the upper right, the hills are spotted with brown.

Eight bars in the colours of the map, for the years 2019 to 2026. The bar of 2025 is by far the highest, and the one of 2026 the lowest.

The bars are the legend, and their height is the area. From the left: 2019 in dark blue, then light blue, blue-green, pale green, yellow, orange (2024), brown (2025), and dark red for 2026. The same in hectares:

ogr2ogr -f CSV /vsistdout/ year.csv -dialect SQLite -oo AUTODETECT_TYPE=YES -sql "select value year, cast(round(count*0.16) as integer) hectares from year where value>0 order by value"
year,hectares
2019,2581
2020,2874
2021,4146
2022,4920
2023,4204
2024,4050
2025,8783
2026,692

Look before moving on. There are three different patterns in this picture.

  1. The narrow strips. They lie along the valleys, side by side, and some of them change every year. Such a regular pattern is the work of people. These hills were planted with eucalyptus for pulp (ledger L135), and the strips look like its harvest. After some years, the trees are tall again, and they can be cut again. So a strip here does not mean that a natural forest was lost. It is more similar to the harvest of a field.
  2. The orange area of 2024, beside the strips. It is one piece of about 2,000 hectares, and its trees were lost within one year, with the same fine lines between. There was a loss here before, mostly between 2007 and 2012 (ledger L137), and the trees had grown again. The satellite data do not show what was done there in 2024, and no source for it was found for this chapter.
  3. The brown spots of 2025, around the lake and on Samosir. They are small, and there are thousands of them, without a pattern. In July 2025, there were fires on the dry hills here, two of them with 40 and 50 hectares (ledger L136). But probably not all of these spots were burnt. The more likely cause is dry weather. Of the 15 clear days of 2025, 10 were between June and October. In the other years, it was 4 to 8. The median of a year is only the median of its clear days.

The same line has found all three, and it can not separate them. It shows that the value fell, and when. For the cause, you need other sources.

Is at least the year right? A research group at the University of Maryland maps the loss of trees for the whole world, with other satellites (ledger L137). It records only the first loss of each place since 2001. For 82 percent of the cells of 2019 to 2024 in this chapter, this was before 2019, so trees were lost there before. This is normal for a plantation. Where both maps have a loss between 2019 and 2024, the year is the same in 63 percent of the cells, and not more than one year apart in 88 percent.

6. A canal becomes wider

In section 2, there was a red strip at Pangururan. Cut this place out of the old map, and make it eight times larger:

gdal raster pipeline read toba_map.jpg ! clip --window 1560,1200,110,110 ! resize --size 880,880 -r nearest ! write neck.png --overwrite

A strongly enlarged piece of the old map. Two blue bays, above and below, are joined by a short blue channel. A thin black road crosses it, beside the yellow town and a red star.

Look before moving on. Under the thin black road, there is a blue channel from one bay to the other. It is a canal, the Tano Ponggol. It was dug in the early 20th century, through the narrow strip of land that joined Samosir to the mainland of Sumatra. So Samosir is an island because of this canal.

On the map, the canal is more than 200 m wide. In reality, it was 25 to 30 m wide, which would be a tenth of a millimetre here, too thin to print in blue. A map shows that an object exists. It often does not show its true width.

The canal was also only 3 m deep. From the end of 2017 on, the government made it wider and deeper, for ships (ledger L138). Is this work visible in the satellite images?

days.csv has 12 days without a cloud over the canal. The window is only 1.2 km wide. The sheet is made in the same way as in section 3:

ogr2ogr -overwrite film.gpkg days.csv -dialect SQLite -sql "select 'vrt:///vsicurl/'||folder||'TCI.tif?projwin=465000,289600,466200,288100&r=cubic&outsize=240,300&a_ullr='||x||','||y||','||(x+240)||','||(y-300) location, buildmbr(x,y-300,x+240,y) geom from (select folder, 247*(rowid-1-6*((rowid-1)/6)) x, -307*((rowid-1)/6) y from days)" -nln film -nlt POLYGON -a_srs EPSG:32647

gdal raster pipeline read GTI:film.gpkg ! select --band 1,2,3 ! scale --src-min 0 --src-max 150 --dst-min 0 --dst-max 255 --ot Byte ! write film.jpg --overwrite --config GDAL_DISABLE_READDIR_ON_OPEN=EMPTY_DIR --co QUALITY=90

Twelve small satellite pictures in two rows. In the first, a thin dark line crosses the green land between two bays. In the next ones, it becomes pale and yellow and wider. From the fifth on, a broad dark canal with white banks joins the two bays, and later a white bridge crosses it. In the tenth, the water in the canal is bright yellow-green.

Look before moving on. The pictures are in the order of time. Upper row, from the left: January and June 2018, May 2019, February and June 2020, May 2021. Lower row: June 2022, May 2023, September 2024, July and December 2025, May 2026.

At first there is a thin line. Then the ground is bare, with a yellow basin in it. Then there is water from bay to bay, and the banks are white and straight. In 2022, a round ramp appears beside the canal, and later a new bridge. And in July 2025, the whole canal is yellow-green. In the same month, many fish died in the lake near Pangururan, and the colour of the water had changed (ledger L139).

The area of the water can also be measured. Water is nearly black in the near infrared. Take a box of 500 m in the middle of the canal, put the 12 boxes side by side, and count the dark cells in each:

ogr2ogr -overwrite strip.gpkg days.csv -dialect SQLite -sql "select day, 'vrt:///vsicurl/'||folder||'B08.tif?projwin=465300,288980,465800,288480&a_ullr='||x||',50,'||(x+50)||',0' location, buildmbr(x,0,x+50,50) geom from (select day, folder, 50*(rowid-1) x from days)" -nln strip -nlt POLYGON -a_srs EPSG:32647

gdal raster calc -i A=GTI:strip.gpkg -o wet.tif --calc "(A<1000) ? 1 : 0" --ot Byte --nodata none --overwrite --config GDAL_DISABLE_READDIR_ON_OPEN=EMPTY_DIR

gdal raster zonal-stats wet.tif wet.csv --zones strip.gpkg --include-field day --stat sum --overwrite

ogr2ogr -f CSV /vsistdout/ wet.csv -dialect SQLite -oo AUTODETECT_TYPE=YES -sql "select day, sum/100.0 hectares, substr('####################################',1,cast(sum/10 as integer)) water from wet order by day"
day,hectares,water
2018/01/07,0.01,
2018/06/06,0.86,########
2019/05/02,0.58,#####
2020/02/16,2.47,########################
2020/06/15,2.6,##########################
2021/05/01,2.69,##########################
2022/06/25,2.55,#########################
2023/05/16,3.15,###############################
2024/09/02,3.45,##################################
2025/07/24,3.31,#################################
2025/12/01,3.6,####################################
2026/05/22,3.45,##################################

The table strip.gpkg is used in two ways. For calc it is a raster with 12 pictures in it (GTI:), and for zonal-stats it is a layer with 12 boxes, and each has a day.

In January 2018, there is nearly no water. The old canal is narrow, with plants on both sides, and hardly any cell of 10 m contains only water. By February 2020, most of the water is there. On the later days, the box has between 2.5 and 3.6 hectares of it, and a ship can sail around Samosir again.

Without a connection, use offline_strip.tif in place of GTI:strip.gpkg in the second line.

7. Old and new in one picture

At the beginning of this chapter, the old map and the satellite image could not be placed over each other. Now it is easy, because old.tif and today.tif have the same cells. How can one picture show both?

One of them can be half transparent. Then neither of them is clear. The other way is to divide the picture into parts that show the old map and the satellite image in turns:

gdal raster calc -i A=old.tif -i B=today.tif -o rays.tif --calc "(sin(12*atan2(_CENTER_Y_-288700,_CENTER_X_-465700))>0) ? A : min(255,40+B*1.5)" --ot Byte --overwrite

gdal raster resize rays.tif rays.jpg --size 1400,1200 -r average --overwrite --co QUALITY=85

Lake Toba, divided into 24 rays from one point, the canal of Pangururan. Every second ray shows the old printed map with its blue water, brown hills and names, and the others show the dark lake and green land of the satellite image. The shore continues from ray to ray without a break.

Part What it does
_CENTER_X_, _CENTER_Y_ in calc, the coordinates of the middle of each cell
atan2(...) the direction from the canal to this cell
sin(12*...)>0 true and false in turns, 12 times each, once around the circle
40+B*1.5 makes the dark satellite image brighter

Look before moving on. Follow the shore from ray to ray. It is nearly continuous. Between the two lie probably about seventy years, and they were made by other people, with other machines and another datum. The shore is the same.

All rays meet at the canal. This is the place where the shore has really changed.

Try it yourself

  • Your own place. In the search of section 3, change the bbox to your town, in degrees, and then change the projwin to a window near it, in metres. How many clear days do you find? (If your box lies in two tiles, filter one of them: the name of the tile is in the id of an image.)
  • Without the mask. In section 4, leave the condition out: --calc "100*(N-S)/(N+S)" --nodata none. Make the median again. Where are remains of the clouds?
  • Another limit. In section 5, write M>=30, and then M>=10. Which of the three patterns disappears first, and which one stays?
  • The other direction. Where did the value rise most, and when? In the line of drop.tif, use (B>35) ? B-A : 0.
  • Rings. In section 7, use rings in place of rays: sin(sqrt((_CENTER_X_-465700)^2+(_CENTER_Y_-288700)^2)/1200)>0.
  • Four points. Keep only the four crossings nearest to the corners of the map in a file four.csv, use them for a new map4.tif, and warp it without -tps. How large is the error of the shore now?

Checkpoint

The cell below stops with an error if the results are not what this chapter expects.

import csv

def table(name):
    with open(name) as f:
        return list(csv.DictReader(f))

# The two lakes must cover each other
share = {x["value"]: float(x["count"]) * 0.0016 for x in table("share.csv")}
assert share["3"] > 1080 and share["1"] + share["2"] < 60, "the old lake and the new one should nearly be the same"

days = [x["day"] for x in table("visits.csv")]
assert 70 < len(days) < 95 and len(set(days)) == len(days), "there should be about 81 visits, each day once"

area = {x["value"]: float(x["count"]) * 0.16 for x in table("year.csv") if x["value"] != "0"}
assert max(area, key=area.get) == "2025", "2025 should have the largest area"
assert 3500 < area["2024"] < 4600, "2024 should have about 4,000 hectares"

water = [float(x["sum"]) / 100 for x in table("wet.csv")]
assert water[0] < 0.1 and min(water[4:]) > 2.3, "the canal should open between 2018 and 2020"

pictures = ("darts.jpg", "shore.jpg", "sheet.jpg", "nine.jpg", "years.png", "film.jpg", "rays.jpg")
assert all((WORK / f).stat().st_size > 10_000 for f in pictures)
print(f"checkpoint passed: {share['3']:,.0f} km2 of water then and now; {len(days)} visits; {area['2024']:,.0f} hectares fell in 2024; the canal grew from {water[0]:.2f} to {water[-1]:.2f} hectares in its box")
print(f"time since the first cell: {time.perf_counter() - T0:.0f} s")
checkpoint passed: 1,114 km2 of water then and now; 81 visits; 4,050 hectares fell in 2024; the canal grew from 0.01 to 3.45 hectares in its box
time since the first cell: 258 s

Troubleshooting

Symptom Cause Fix
The map is strongly distorted A wrong control point, often with x and y swapped Draw the errors as in section 1. A wrong point has a much longer shape than its neighbours
The search gives an empty table bbox is west, south, east, north, in degrees; or the dates have another form Open the address in a browser, and read the answer
Everything has changed at once between 2021 and 2022 The 1,000 of section 3 The where of section 3
gdal raster stack is very slow GDAL lists the folder of each image first --config GDAL_DISABLE_READDIR_ON_OPEN=EMPTY_DIR
The map without clouds has holes These cells have no clear day Take more days: limit 15
A sheet is empty, or has one picture only The box in the table is not where a_ullr puts the picture Both need the same four numbers
zonal-stats does not finish The name ends with .gti.gpkg, so GDAL reads the boxes as a raster Use a plain .gpkg, and write GTI: only where you want the raster

What comes next

This chapter showed where and when the land has changed. But a map of changes contains no information about people. Chapter 15: Walking times to safety in a tsunami combines height, distance and people to answer one question, and then tests the answer.

Old map: U. S. Army Map Service, public domain, joined by the user Geoethno, Wikimedia Commons. Satellite images: contains modified Copernicus Sentinel data 2018 to 2026, from the Sentinel-2 COGs on AWS, found with Earth Search by Element 84. 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.