Skip to main content

Chapter 10: Contour lines with light and shade

Chapter 10: Contour lines with light and shade

TipAt a glance
  • In this series: Part IV, Surfaces. In Chapter 9, lines at equal distances showed the heights. In this chapter, each line has one height, and its direction shows on which side the land is higher
  • You will build: The volcanoes of Bali drawn with contour lines that are light on one side and dark on the other, and with strokes as on old military maps; a map of summits and holes; and contour lines for the number of people
  • You need: Chapter 0, for the environment, and section 5 of Chapter 1, for lines that work in every shell. Chapter 9 explains a raster as a table
  • Time to run: The commands took about two minutes when tested, including 9 MB of downloads, or none with the copy in the folder
  • Level: Intermediate; a little geometry decides the colour of each line

A contour line joins places of equal height. It is the most exact way to draw a mountain, but many readers find it hard to see the form of the land in it.

A contour line has more than a height. It also has a direction, and the slope beside it faces north, or south, or any other way. In this chapter, the direction decides how each piece of a line is drawn. The result is a relief without any shading, made of lines alone. After that, the chapter uses the lines to find summits and craters, to measure a lake, and to draw a number that is not a height.

NoteLearning objectives

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

  • make contour lines and bands of height from a relief, and smooth it first;
  • find out from a line which side of it is higher;
  • draw contours in light and dark according to the direction of the light, and change this direction;
  • draw a relief with strokes that run downhill, as in old military maps;
  • find summits and holes by their innermost lines;
  • measure a lake by its shore line;
  • draw numbers with a huge range, with a line for each doubling.

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/ch10. 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("10")
print("working folder:", WORK.name, "| files copied there:", sorted(f.name for f in (ROOT / "sample-data/ch10").iterdir()))
working folder: ch10 | files copied there: ['double.txt', 'light.txt', 'offline_bali.tif', 'people.tif', 'plain.txt', 'strokes.txt', 'warm.txt']

Warm-up

A few short commands first, in the form of Chapter 0. The folder has the relief of two volcanoes in Bali, in metres. Light, colour, and both together:

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

gdal raster color-map offline_bali.tif colour.tif --color-map warm.txt --overwrite

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

gdal raster resize shaded.tif shaded.png --size 760,0 -r average --overwrite

A coloured and shaded relief of north-east Bali. A large old crater with a small volcano inside lies in the middle, and the cone of Agung with its round crater at the lower right.

Look before moving on. The picture shows clearly what is high and what is steep. But how high is the edge of the crater? The picture does not contain this number. Contour lines do, and they are one command, too:

gdal raster contour offline_bali.tif simple.gpkg --interval 100 --elevation-name height --overwrite

gdal vector info simple.gpkg --summary
INFO: Open of `simple.gpkg'
      using driver `GPKG' successful.
1: contour (Line String)

Shading shows the form without the numbers. Contour lines show the numbers, but the form is hard to see. This chapter makes lines that show both.

1. Lines of equal height

The place is the north-east of Bali, with two volcanoes: Batur inside its huge old crater, and Agung, the highest mountain of the island. The relief is the Copernicus model (ledger L80):

gdalwarp -q -overwrite -t_srs EPSG:32750 -te 306000 9068000 344000 9100000 -tr 25 25 -r cubic /vsicurl/https://copernicus-dem-30m.s3.amazonaws.com/Copernicus_DSM_COG_10_S09_00_E115_00_DEM/Copernicus_DSM_COG_10_S09_00_E115_00_DEM.tif bali.tif

gdal raster pipeline read bali.tif ! resize --size 506,426 -r average ! materialize ! resize --size 1520,1280 -r cubicspline ! write soft.tif --overwrite

gdal raster contour soft.tif bali.gpkg --interval 50 --elevation-name h --output-layer line --overwrite

gdal raster contour soft.tif band.gpkg --levels "MIN,1,250,500,750,1000,1250,1500,1750,2000,2250,2500,2750,MAX" --polygonize --min-name lo --max-name hi --output-layer band --overwrite

ogr2ogr -update -overwrite bali.gpkg band.gpkg band

gdal raster contour bali.tif lake.gpkg --levels 1031.5 --elevation-name h --output-layer shore --overwrite

ogr2ogr -update -overwrite bali.gpkg lake.gpkg -sql "select st_makepolygon(geom) geom from shore where st_isclosed(geom) and st_npoints(geom)>3 and st_contains(st_makepolygon(geom), makepoint(324400,9086700,32750))" -nln lake
Line What it does
1 fetches the window and projects it to metres, in cells of 25 m. Without a connection, use offline_bali.tif as bali.tif
2 smooths it a little: small with the mean, and large again with smooth curves, as in Chapter 17
3 a line every 50 m, with the height in the column h
4, 5 with --polygonize, the areas between the levels. MIN and MAX stand for the lowest and the highest value
6, 7 the lake, from a single line. Section 6 explains it

The second line is important. The model has every tree and every house in it, and without smoothing the contour lines have many small bends. Draw the usual map, with a thicker line every 250 m:

gdal pipeline read bali.gpkg ! sql "select 3 v, geom from band where hi<=1 union all select 3, geom from lake union all select 1, st_buffer(geom,5) from line where h>0 union all select 2, st_buffer(geom,11) from line where h>0 and mod(h,250)=0" ! rasterize --attribute-name v --init 0 --ot Byte --size "5700,4800" --extent "306000,9068000,344000,9100000" ! edit --nodata none ! color-map --color-map plain.txt ! materialize ! resize --size "1900,1600" -r average ! write plain.png --overwrite

A contour map in brown lines on cream paper. A ring of close lines in the upper middle surrounds a flat area with a small cone in it. At the lower right, a large cone is drawn by many closed lines. The sea is pale blue at the upper right.

The map contains all the heights, but it takes some time to recognise the form of the land.

2. Light from the north-west

The GDAL manual describes the rule that this section uses: contour lines are written so that the higher side is on the right (ledger L82). In the direction of the line, the mountain is on the right, and the slope goes down to the left. So the direction of each small piece of a line shows which way its slope faces.

First, cut the lines into their smallest pieces, with two points each:

ogr2ogr -update -overwrite bali.gpkg bali.gpkg -sql "select h, dissolvesegments(st_simplify(geom,6)) geom from line where h>0" -nln piece -explodecollections -nlt LINESTRING

ogr2ogr -f CSV /vsistdout/ bali.gpkg -sql "select (select count(*) from line where h>0) lines, count(*) pieces, round(avg(st_length(geom))) mean_length_m from piece"
lines,pieces,mean_length_m
288,47427,89

Now let the light come from the north-west, the upper left corner, as most maps with shading do (ledger L83). For each piece, one number describes how much its slope faces the light: 1 is straight towards it, -1 is straight away, and 0 is sideways. With the direction of the piece as dx and dy, and the direction of the light as a, it is

(cos(a)*dx - sin(a)*dy) / length

Use this number for both the brightness and the width. Slopes that face the light get wide white lines, slopes that face away from it wide dark ones, and all others thin grey ones. The bands of height lie below in pale colours:

gdal pipeline read bali.gpkg ! sql "select case when hi<=1 then 1 else 2+cast(lo/250 as integer) end v, geom from band union all select 1, geom from lake union all select 20+min(7,cast((c+1)*4 as integer)), st_buffer(geom, 2+14*abs(c),1) from (select geom, (cos(radians(315))*(st_x(st_endpoint(geom))-st_x(st_startpoint(geom)))-sin(radians(315))*(st_y(st_endpoint(geom))-st_y(st_startpoint(geom))))/st_length(geom) c from piece where st_length(geom)>0)" ! rasterize --attribute-name v --init 0 --ot Byte --size "5700,4800" --extent "306000,9068000,344000,9100000" ! edit --nodata none ! color-map --color-map light.txt ! materialize ! resize --size "1900,1600" -r average ! write lit.png --overwrite

The same area as a relief that looks three-dimensional. White lines draw the north-western slopes and black lines the south-eastern ones. The old crater is a deep bowl with a small cone in it, and the large volcano at the lower right rises to a pale summit with a round crater.

Part Meaning
st_x(st_endpoint(geom))-st_x(st_startpoint(geom)) dx, how far the piece runs to the east. The other part is dy, to the north
315 the direction of the light as on a compass: north is 0, east is 90, and north-west is 315
20+min(7,cast((c+1)*4 as integer)) eight steps of grey, from 20 (dark) to 27 (white)
2+14*abs(c) the width: 2 m for a slope that stands sideways, and up to 16 m for the others

Look before moving on. There is no shading in this picture. All the light and dark parts are contour lines, and the heights can still be read from them. The method is called illuminated contours. The Japanese cartographer Kitiro Tanaka published it in 1950 (ledger L84).

3. Light from the opposite side

The direction is a number, so change it. Let the light come from the opposite corner, at 135 degrees, the south-east. Nothing else changes:

gdal pipeline read bali.gpkg ! sql "select case when hi<=1 then 1 else 2+cast(lo/250 as integer) end v, geom from band union all select 1, geom from lake union all select 20+min(7,cast((c+1)*4 as integer)), st_buffer(geom, 2+14*abs(c),1) from (select geom, (cos(radians(135))*(st_x(st_endpoint(geom))-st_x(st_startpoint(geom)))-sin(radians(135))*(st_y(st_endpoint(geom))-st_y(st_startpoint(geom))))/st_length(geom) c from piece where st_length(geom)>0)" ! rasterize --attribute-name v --init 0 --ot Byte --size "5700,4800" --extent "306000,9068000,344000,9100000" ! edit --nodata none ! color-map --color-map light.txt ! materialize ! resize --size "1900,1600" -r average ! write wrong.png --overwrite

The same map with black and white exchanged. Many people now see the large volcano as a deep pit, and the old crater as a raised plateau with a hollow in it.

Look before moving on. What do you see at the lower right? For many people, the volcano now looks like a hole, and the old crater like a hill. Every line is correct, and the mountain still looks inverted.

People expect light from above. When it comes from below, many see the form the other way round, so that the light still seems to come from above. This is why maps are lit from the upper left, although in the northern part of the world the sun never stands there (ledger L83). On Bali, south of the equator, it can: on a June afternoon, the sun is in the north-west. If you see a satellite picture in which the rivers run on the ridges, turn it by 180 degrees.

4. Strokes that run downhill

Before contour lines were common, engravers drew mountains with hachures: short strokes in the direction of the steepest slope, and thicker where it is steeper. In 1799, Johann Georg Lehmann gave them exact rules (ledger L85).

Three things are needed: places to start, the direction, and the steepness. The places lie on the contour lines, one every 90 m. The other two come from the relief:

gdal raster slope soft.tif slope.tif --overwrite

gdal raster aspect soft.tif aspect.tif --overwrite

gdal raster as-features slope.tif slope.gpkg --output-layer slope --geometry-type none --include-row-col --overwrite

gdal raster as-features aspect.tif aspect.gpkg --output-layer aspect --geometry-type none --include-row-col --overwrite

ogr2ogr -update -overwrite bali.gpkg slope.gpkg slope

ogr2ogr -update -overwrite bali.gpkg aspect.gpkg aspect

ogr2ogr -update -overwrite bali.gpkg bali.gpkg -sql "select st_line_interpolate_equidistant_points(geom, 90.0) geom from line where h>0 and st_length(geom)>300" -nln start -explodecollections -nlt POINT -dim XY

ogr2ogr -update -overwrite bali.gpkg bali.gpkg -sql "select z slope, makeline(makepoint(x,y), makepoint(x+sin(a)*l, y+cos(a)*l)) geom from (select st_x(d.geom) x, st_y(d.geom) y, s.band_1 z, radians(a.band_1) a, min(260, 46/tan(radians(s.band_1))) l from start d join slope s on s.row=cast((9100000-st_y(d.geom))/25 as integer) and s.col=cast((st_x(d.geom)-306000)/25 as integer) join aspect a on a.row=s.row and a.col=s.col where s.band_1>6)" -nln stroke -nlt LINESTRING

ogr2ogr -f CSV /vsistdout/ bali.gpkg -sql "select count(*) strokes, round(avg(slope)) mean_slope, round(max(slope)) steepest from stroke"
strokes,mean_slope,steepest
40804,20,62

slope is the steepness in degrees. aspect is the direction in which the ground goes down, as on a compass. Both rasters become tables, and a join by row and column reads them at each starting point. This is the method of Chapter 9.

46/tan(slope) is the length. The next contour line lies 50 m lower, and on a slope of this steepness it is 50/tan(slope) metres away. The stroke ends just before it. Where the ground is nearly flat, below 6 degrees, there are no strokes, and the paper stays white:

gdal pipeline read bali.gpkg ! sql "select 2 v, geom from band where hi<=1 union all select 2, geom from lake union all select 1, st_buffer(geom, 1.5+0.42*slope,1) from stroke" ! rasterize --attribute-name v --init 0 --ot Byte --size "5700,4800" --extent "306000,9068000,344000,9100000" ! edit --nodata none ! color-map --color-map strokes.txt ! materialize ! resize --size "1900,1600" -r average ! write strokes.png --overwrite

The same area drawn with tens of thousands of short dark strokes on cream paper. They run from the summit of the large volcano in all directions. Thick short strokes mark the steep inner wall of the old crater, and the flat land is empty.

Look before moving on. No lines of equal height were drawn here, and their positions are still visible, because the strokes begin on them. The steep inner wall of the old crater is nearly black. The flat lava around Batur is empty, and so is the lake.

The method also has a weakness. It shows clearly what is steep. But is the round form at the lower right a mountain or a hole? The strokes are the same for both.

5. Summits and holes

A summit has a property that a program can find: a closed contour line with no other one inside. A crater has the same property. The direction of the line distinguishes the two. Around a summit, the line runs clockwise, with the higher side on its right. Around a hole, it runs the other way:

ogr2ogr -update -overwrite bali.gpkg bali.gpkg -sql "with r as materialized (select fid id, h, st_makepolygon(geom) geom from line where h>0 and st_isclosed(geom) and st_length(geom)>400) select id, h, st_ispolygoncw(geom) summit, round(st_area(geom)/1e4) hectares, st_centroid(geom) geom from r a where not exists (select 1 from r b where b.id<>a.id and st_within(b.geom,a.geom))" -nln spot -nlt POINT

ogr2ogr -f CSV /vsistdout/ bali.gpkg -sql "select case summit when 1 then 'summits' else 'holes' end kind, count(*) number, max(h) highest_line_m from spot group by 1"
kind,number,highest_line_m
holes,29,2550
summits,37,2950
gdal pipeline read bali.gpkg ! sql "select 3 v, geom from band where hi<=1 union all select 3, geom from lake union all select 1, st_buffer(geom,5) from line where h>0 union all select 2, st_buffer(geom,11) from line where h>0 and mod(h,250)=0 union all select case summit when 1 then 4 else 5 end, st_buffer(geom,170) from spot" ! rasterize --attribute-name v --init 0 --ot Byte --size "5700,4800" --extent "306000,9068000,344000,9100000" ! edit --nodata none ! color-map --color-map plain.txt ! materialize ! resize --size "1900,1600" -r average ! write spots.png --overwrite

The contour map of section 1 with red and blue dots. Red dots are on the large volcano, on the small cone, and along the rim of the old crater. A blue dot marks the crater of the large volcano, and another one the lake in the old crater, which is pale blue like the sea. More blue dots lie in the valleys of the south and west.

Look before moving on. Red is a summit, and blue is a hole. Agung has its crater as a blue dot between two red ones. The rim of the old crater has a row of summits. The blue dot in the middle is the lake.

And the blue dots in the valleys of the south? We found no sign that there are craters. A likely reason is that the relief is a model of the surface, with trees and bridges. Where they cross a narrow valley, the data has a barrier, and behind it a hole that does not exist. Before a calculation of water flow on a relief, such holes have to be filled.

6. The shore is a contour line

The surface of a lake is level. So its shore is a contour line, and section 1 drew exactly this one: read the height of the water from the original relief, draw a single line one metre above it (--levels 1031.5), and keep the closed line around a point in the lake. The line gives the area of the lake and the length of its shore:

gdallocationinfo -valonly -geoloc bali.tif 324400 9086700

ogr2ogr -f CSV /vsistdout/ lake.gpkg -sql "select round(st_area(st_makepolygon(geom))/1e6,1) km2, round(st_length(geom)/1000,1) km_of_shore, st_ispolygoncw(st_makepolygon(geom)) clockwise from shore where st_isclosed(geom) and st_npoints(geom)>3 and st_contains(st_makepolygon(geom), makepoint(324400,9086700,32750))"
1030.5
km2,km_of_shore,clockwise
16.1,21.2,0

Is it right? For Lake Batur, an encyclopaedia gives a surface at 1,031 m and an area of 15.9 km2 (ledger L86). Our line gives 1,030.5 m and 16.1 km2. It lies one metre higher than the water, so it must be a little larger. And it does not run clockwise: the lake is a hole.

How much land lies at which height? The areas of the bands of section 1 show it:

ogr2ogr -f CSV /vsistdout/ bali.gpkg -sql "select case when hi<=1 then 'sea' else cast(round(lo) as integer)||' to '||cast(round(hi) as integer)||' m' end height, round(st_area(geom)/1e6,1) km2 from band order by lo"
height,km2
sea,118.3
1 to 250 m,103.4
250 to 500 m,95.8
500 to 750 m,238.7
750 to 1000 m,225.7
1000 to 1250 m,267.2
1250 to 1500 m,112.7
1500 to 1750 m,26.9
1750 to 2000 m,10.5
2000 to 2250 m,6.6
2250 to 2500 m,4.7
2500 to 2750 m,3.8
2750 to 2993 m,1.8

Two thirds of this land lie between 500 and 1,250 m, and only 17 km2 above 2,000 m. The top of a high mountain covers only a small area.

7. A line for each doubling

Contour lines are not only for heights. They can be made from any raster. Take the people of Java from Chapter 9 (people.tif, ledger L79). Here a line every 50 would be useless: some cells have very few people, and others more than 16,000. For numbers with such a range, let the value of each line be twice the one before it:

gdal raster pipeline read people.tif ! resize --size 588,198 -r average ! materialize ! resize --size 2352,792 -r cubicspline ! write people_soft.tif --overwrite

gdal raster contour people_soft.tif people.gpkg --exp-base 2 --elevation-name n --output-layer line --overwrite

ogr2ogr -f CSV /vsistdout/ people.gpkg -sql "select group_concat(n, ' ') people_in_a_cell from (select distinct n from line order by n)"

gdal pipeline read people.gpkg ! sql "select min(12,max(1,cast(log(n)/log(2)+0.5 as integer)-2)) v, st_buffer(geom,0.0016+0.00022*log(n)/log(2),2) geom from line where n>=8 order by n" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "7840,2360" --extent "104.9,-8.85,114.7,-5.9" ! edit --nodata none ! color-map --color-map double.txt ! materialize ! resize --size "1960,590" -r average ! write people.png --overwrite
people_in_a_cell
1.0 2.0 4.0 8.0 16.0 32.0 64.0 128.0 256.0 512.0 1024.0 2048.0 4096.0 8192.0 16384.0

Java on black, drawn with bright lines from blue and violet to pale yellow. Dense pale lines surround Jakarta, Bandung, Semarang, Yogyakarta, Surakarta, Surabaya and Malang. Dark empty spots with a blue edge lie scattered over the island.

--exp-base 2 makes the levels 1, 2, 4, 8 and so on. A cell is about 900 m wide, so the numbers are a little larger per square kilometre.

Look before moving on. This map is read like a map of mountains. Where many lines lie close together, the number of people rises quickly: at the edges of the cities, and at the coast. There are also dark spots with a blue edge, where the number falls to zero. Compare them with the relief of Chapter 9: of the 19 empty spots larger than 25 km2, 18 hold a mountain higher than 1,200 m (ledger L87). Many people live around the mountains, and nobody on their upper parts.

Try it yourself

  • Light from the west. Let the light come from 270 degrees. Which valleys appear, and which disappear?
  • Finer lines. Make a line every 25 m in section 1, and halve the widths in section 2.
  • Your own mountain. Change the tile, the window and the UTM zone. The two corner numbers of section 4 belong to the window.
  • Thicker strokes. Change the width in section 4, so that a slope of 45 degrees fills the paper. The strokes are 90 m apart.
  • Another base. --exp-base 3 draws fewer lines. Which details are missing?

Checkpoint

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

import csv
import io

def rows(sql, dataset="bali.gpkg"):
    """The rows of a query, as dictionaries."""
    return list(csv.DictReader(io.StringIO(oneline.run(f'ogr2ogr -f CSV /vsistdout/ {dataset} -sql "{sql}"'))))

# The rule that everything rests on: the higher side of a line is on its right, so a ring around Agung runs clockwise
ring = rows("select st_ispolygoncw(st_makepolygon(geom)) cw from line where h=2000 and st_isclosed(geom) order by st_length(geom) desc limit 1")
assert ring[0]["cw"] == "1", "the line around the summit should run clockwise"

# The highest summit must be Agung, and it must have a crater beside it
top = rows("select h, st_x(geom) x, st_y(geom) y from spot where summit=1 order by h desc limit 1")[0]
hole = rows("select h, st_x(geom) x, st_y(geom) y from spot where summit=0 order by h desc limit 1")[0]
apart = ((float(top["x"]) - float(hole["x"])) ** 2 + (float(top["y"]) - float(hole["y"])) ** 2) ** 0.5
assert float(top["h"]) >= 2900 and apart < 2000, "Agung and its crater should be the highest of their kind"

lake = float(rows("select st_area(st_makepolygon(geom))/1e6 a from shore where st_isclosed(geom) and st_npoints(geom)>3 and st_contains(st_makepolygon(geom), makepoint(324400,9086700,32750))", "lake.gpkg")[0]["a"])
assert 15.5 < lake < 16.8, "Lake Batur should have about 16 km2"

area = float(rows("select sum(st_area(geom))/1e6 a from band")[0]["a"])
assert abs(area - 38 * 32) < 15, "the bands should fill the window"

pictures = ("plain.png", "lit.png", "wrong.png", "strokes.png", "spots.png", "people.png")
assert all((WORK / f).stat().st_size > 10_000 for f in pictures)
print(f"checkpoint passed: lines run clockwise round a summit; Agung and its crater are {apart:,.0f} m apart; Lake Batur has {lake:.1f} km2")
print(f"time since the first cell: {time.perf_counter() - T0:.0f} s")
checkpoint passed: lines run clockwise round a summit; Agung and its crater are 876 m apart; Lake Batur has 16.1 km2
time since the first cell: 130 s

Troubleshooting

Symptom Cause Fix
Light and dark are exchanged Another tool has reversed the direction of the lines Make them again with gdal raster contour, or change the sign of the number
--polygonize with one level gives nothing It makes areas between levels, and one level has no second one MIN and MAX at the ends of the list
The lines have many small bends Trees and houses in the relief Smooth it, as in line 2 of section 1
The strokes point in wrong directions aspect and the window do not belong together Use the same corner and cell size in both joins
A chain of holes along the coast The sea is level 0 with tiny waves in the data h>0

What comes next

In this chapter, the direction of the slope decided how a line is drawn. Chapter 11: Terrain commands for other data uses the commands for mountains, slope, aspect and shade, for data that has nothing to do with mountains.

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. People: WorldPop, estimates for 2025, release R2025A v1, CC BY 4.0.