How to Extract Contours from Historical Maps and Add Them to Interactive Maps

A free step-by-step tutorial for libraries, archives and researchers

📋 Tutorial Overview

⏱️ Time Required: 2-3 hours
💰 Cost: $0 (free software)
🎯 Difficulty: Intermediate
🛠️ Coding Required: Running a short Python script
1
Choose
2
Georeference
3
Colour
4
Extract
5
Map
6
Publish
1

Choose and Prepare the Historical Map

The quality of the contour depends on the scan, so choose the map carefully before you open any software. A good candidate is a large, flat, high-resolution scan on which the area you want is clearly separated from its surroundings, either by a colour wash or by a clear ink outline.

1.1 Check the scan

  • At least 3,000 pixels along the long edge (more for large areas)
  • No heavy folds, shadows or cropped corners in the part you need
  • Towns, rivers or coastlines that still exist today, so you can anchor the map to the real world in the next step
  • The region you want is filled with its own colour, or has a continuous border line

1.2 Find maps you may reuse

Large libraries publish high-resolution scans of historical maps, for example the Library of Congress Geography and Map Division and the David Rumsey Map Collection. Reuse terms differ from map to map, so read the rights statement on each item and note it down together with the full citation. You will store both with the contour in step 6.

Keep the original file

Never edit the downloaded scan itself. Work on a copy and keep the original untouched, with its source link, in a folder named after the map.

2

Georeference the Map in QGIS

A scanned map is just a picture. Georeferencing gives each pixel a real latitude and longitude, so that the contour you extract later lands in the right place on a modern interactive map. QGIS is free and includes a tool for this.

2.1 Install QGIS and open the Georeferencer

Download QGIS from qgis.org. Then choose Layer → Georeferencer, open your map copy with File → Open Raster and set the target CRS to EPSG:4326 (WGS 84, plain latitude and longitude).

2.2 Add control points

Click a recognisable spot on the scan, choose From Map Canvas and click the same spot on a modern base map (use the XYZ Tiles layer for OpenStreetMap). Repeat for 10 to 20 points.

  • Use features that have not moved: river mouths and confluences, capes, island tips, old cities that still exist
  • Do not use borders. They are exactly what you want to measure, and they changed over time
  • Spread the points over the whole map, including near the edges, not only in the centre

2.3 Choose the transformation

Open Transformation Settings. For old hand-drawn maps, which stretch unevenly, Thin Plate Spline usually fits best. If the map was drawn carefully and is close to a modern projection, Polynomial 1 is simpler and safer. Set resampling to Cubic, compression to LZW, tick “Load in QGIS when done”, and press Start Georeferencing. The result is a GeoTIFF file.

Check the result before you go on

Put the georeferenced map over OpenStreetMap and lower its opacity. Coastlines, rivers and cities should line up. If one corner is off, add a few control points there and run it again. Expect old maps to be off by several kilometres in places. That is the map, not your mistake.

2.4 Optional: match the web map projection

Web maps such as Leaflet draw in Web Mercator. If you plan to show the scan itself under the contour, reproject it once with GDAL (installed with QGIS):

gdalwarp -t_srs EPSG:3857 -r cubic -co COMPRESS=LZW map_georef.tif map_webmercator.tif
3

Set Up Python and Find the Region’s Colour

The next steps use a short Python script. You only run it, you do not need to write it. Install Python 3 from python.org if you do not have it, then install the libraries once:

pip install opencv-python rasterio geopandas shapely numpy

Save the script from step 4 as extract_contours.py next to your georeferenced file, which this tutorial calls map_georef.tif. First find the colour of the region you want. Open the GeoTIFF in any image viewer, note the pixel position (x, y) of a spot inside the coloured region, and ask the script for its colour:

python extract_contours.py map_georef.tif --pick 600,300

It prints the red, green and blue values at that pixel, for example RGB at pixel (600, 300) = 225,170,160. You will use those three numbers next.

Maps with outlines but no colour

If your map shows borders as lines on blank paper, colour selection will not work. Trace the outline by hand instead: in QGIS create a new GeoPackage layer of type Polygon, switch on editing, and click along the border with the Add Polygon Feature tool. Export it as GeoJSON and skip straight to step 5.

4

Extract the Contour and Save It as GeoJSON

The script finds all pixels close to your colour, cleans up the specks and ink lines, traces the outline, converts the outline from pixel positions to longitude and latitude using the georeferencing, simplifies it, and saves a GeoJSON file.

extract_contours.py
"""Extract a coloured region from a georeferenced historical map and save it as GeoJSON.

Usage:
  python extract_contours.py map.tif --pick 600,300          # print the colour at pixel (x,y)
  python extract_contours.py map.tif --colour 225,170,160 --name "Ukraine" --year 1795 -o region.geojson
"""
import argparse, json
import cv2, numpy as np, rasterio
import geopandas as gpd
from shapely.geometry import Polygon
from shapely.ops import unary_union

def read_rgb(path):
    with rasterio.open(path) as src:
        rgb = src.read([1, 2, 3]).transpose(1, 2, 0)      # rows, cols, bands
        return rgb, src.transform, src.crs

def colour_mask(rgb, target_rgb, tol_h=6, tol_s=25, tol_v=45):
    """Pixels whose colour is close to target_rgb, compared in HSV so lighting matters less."""
    hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV).astype(int)
    t = cv2.cvtColor(np.uint8([[target_rgb]]), cv2.COLOR_RGB2HSV)[0, 0].astype(int)
    dh = np.minimum(abs(hsv[..., 0] - t[0]), 180 - abs(hsv[..., 0] - t[0]))   # hue is circular
    ok = (dh <= tol_h) & (abs(hsv[..., 1] - t[1]) <= tol_s) & (abs(hsv[..., 2] - t[2]) <= tol_v)
    return (ok * 255).astype(np.uint8)

def clean(mask, close_px=9, min_area=500):
    k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (close_px, close_px))
    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, k)    # fill specks and thin ink lines
    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, k)     # remove stray dots
    n, labels, stats, _ = cv2.connectedComponentsWithStats(mask)
    keep = np.zeros_like(mask)
    for i in range(1, n):
        if stats[i, cv2.CC_STAT_AREA] >= min_area:
            keep[labels == i] = 255
    return keep

def to_polygons(mask, transform, simplify_deg=0.01, min_area=500, min_hole=5000):
    """Mask -> shapely polygons in map coordinates (lon, lat), holes kept."""
    cnts, hier = cv2.findContours(mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
    def geo(c):   # pixel (col,row) -> map x,y, using pixel centres
        return [tuple(transform * (float(x) + 0.5, float(y) + 0.5)) for x, y in c[:, 0, :]]
    polys = []
    for i, c in enumerate(cnts):
        if hier[0][i][3] != -1 or cv2.contourArea(c) < min_area:      # outer contours only
            continue
        holes = [geo(h) for j, h in enumerate(cnts) if hier[0][j][3] == i and cv2.contourArea(h) >= min_hole]   # drops lettering and tiny gaps
        p = Polygon(geo(c), holes)
        polys.append(p if p.is_valid else p.buffer(0))
    merged = unary_union(polys)
    return merged.simplify(simplify_deg, preserve_topology=True)

if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('tif'); ap.add_argument('--pick'); ap.add_argument('--colour')
    ap.add_argument('--name', default='region'); ap.add_argument('--year', type=int)
    ap.add_argument('--tol', default='6,25,45', help='hue,saturation,value tolerance; lower = stricter')
    ap.add_argument('--min-hole', type=int, default=5000, help='smallest hole (in pixels) to keep, e.g. a lake')
    ap.add_argument('--simplify', type=float, default=0.01, help='tolerance in degrees (0.01 is about 1 km)')
    ap.add_argument('-o', '--out', default='region.geojson')
    a = ap.parse_args()
    rgb, transform, crs = read_rgb(a.tif)
    if a.pick:
        x, y = map(int, a.pick.split(','))
        print('RGB at pixel', (x, y), '=', ','.join(map(str, rgb[y, x]))); raise SystemExit
    target = tuple(int(v) for v in a.colour.split(','))
    th, ts, tv = (int(v) for v in a.tol.split(','))
    mask = clean(colour_mask(rgb, target, th, ts, tv))
    cv2.imwrite('mask_preview.png', mask)                  # open this to check what was selected
    geom = to_polygons(mask, transform, a.simplify, min_hole=a.min_hole)
    gdf = gpd.GeoDataFrame([{'name': a.name, 'year': a.year, 'source': a.tif}], geometry=[geom], crs=crs)
    gdf.to_crs(4326).to_file(a.out, driver='GeoJSON')
    print('wrote', a.out, '-', len(geom.geoms) if hasattr(geom, 'geoms') else 1, 'polygon(s)')

Run it with the colour from step 3 and a name and year for the region:

python extract_contours.py map_georef.tif --colour 225,170,160 --name "Ukraine" --year 1795 -o region.geojson

4.1 Look at what was selected

The script also writes mask_preview.png. White pixels are the area it picked. Open it next to the map and check three things:

  • Too much selected (the paper or a neighbouring region is white): make the colour match stricter, for example --tol 4,15,30
  • Too little selected (the region has holes or missing patches): loosen it, for example --tol 8,35,60
  • Lettering and tiny gaps inside the region: these are dropped automatically. Lakes and other real gaps are kept if they are bigger than --min-hole pixels

4.2 Choose how much to simplify

--simplify sets the tolerance in degrees. The default 0.01 is roughly one kilometre, which suits a map of a whole country. Use a smaller number such as 0.002 for a city or a small region. Larger numbers make a smaller, smoother file.

A pink demo region traced as a red outline over a faint scanned map on OpenStreetMap, with a lake kept as a hole
Result on a made-up demo map: the red outline is the extracted contour, the faint pink shape is the scan underneath, and the lake is kept as a hole.
5

Add the Contour to an Interactive Map

GeoJSON is the format web maps understand. This page uses Leaflet, a free JavaScript map library. Save the file below as map.html in the same folder as region.geojson. If you want the scan underneath, also put the image there and change the file name and corner coordinates in the imageOverlay line. If you do not want it, delete that line and the opacity slider for it.

map.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Historical contours on an interactive map</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<style>
  html, body { height: 100%; margin: 0; font-family: system-ui, sans-serif; }
  #map { height: 100%; }
  .panel { position: absolute; z-index: 1000; top: 10px; right: 10px; background: #fff; padding: 10px 12px;
           border-radius: 8px; box-shadow: 0 1px 6px rgba(0,0,0,.3); font-size: 14px; }
  .panel label { display: block; margin-top: 6px; }
</style>
</head>
<body>
<div id="map"></div>
<div class="panel">
  <strong>1795 contour</strong>
  <label>Scanned map opacity <input id="scan" type="range" min="0" max="1" step="0.05" value="0.6"></label>
  <label>Contour opacity <input id="fill" type="range" min="0" max="1" step="0.05" value="0.35"></label>
</div>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
const map = L.map('map').setView([48.5, 31], 6);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; OpenStreetMap contributors', maxZoom: 19 }).addTo(map);

// 1. The georeferenced scan, placed by its corner coordinates [[south, west], [north, east]]
const scan = L.imageOverlay('demo_map.png', [[44, 22], [53, 40]], { opacity: 0.6 }).addTo(map);

// 2. The extracted contour (GeoJSON stores longitude first, Leaflet handles that for us)
const base = { color: '#9b2d20', weight: 2, fillColor: '#d9534f', fillOpacity: 0.35 };
fetch('region.geojson').then(r => r.json()).then(data => {
  const layer = L.geoJSON(data, {
    style: () => base,
    onEachFeature: (f, l) => {
      l.bindTooltip(f.properties.name + (f.properties.year ? ', ' + f.properties.year : ''), { sticky: true });
      l.bindPopup('<b>' + f.properties.name + '</b><br>Year: ' + (f.properties.year || 'n/a') +
                  '<br>Source: ' + f.properties.source);
      l.on('mouseover', () => l.setStyle({ weight: 4 }));
      l.on('mouseout',  () => layer.resetStyle(l));
    }
  }).addTo(map);
  map.fitBounds(layer.getBounds());
  document.getElementById('fill').oninput = e => { base.fillOpacity = +e.target.value; layer.setStyle(base); };
});
document.getElementById('scan').oninput = e => scan.setOpacity(+e.target.value);
</script>
</body>
</html>

Browsers block pages from reading local files, so start a small local web server in that folder and open the address it shows:

python -m http.server 8000
# then open http://localhost:8000/map.html

5.1 What the page does

  • Draws the contour as a coloured shape that you can hover over for its name and year
  • Opens a popup with the name, year and source when you click it
  • Lets you fade the scanned map and the contour in and out with two sliders, so you can judge how well they fit the modern map

Several maps, several periods

Run the script once per map and region, giving each its own --year. Save the results as separate GeoJSON files, or merge them into one file with a year property. Then add a slider that calls layer.setStyle or hides features whose year does not match, and you have a time slider for historical borders.

6

Publish and Document Your Work

A contour is only useful to other people if they can tell where it came from and how far to trust it.

6.1 Publish for free on GitHub Pages

Create a repository, add map.html, region.geojson and any images, then push them:

git init
git add map.html region.geojson
git commit -m "Historical contour map"
git branch -M main
git remote add origin https://github.com/YOUR-NAME/YOUR-REPO.git
git push -u origin main

On GitHub open Settings → Pages, choose the main branch and save. After a minute or two the map is at https://YOUR-NAME.github.io/YOUR-REPO/map.html. If the page is called index.html the address is shorter.

6.2 Record where each contour came from

Keep these facts in the GeoJSON properties or in a README next to it:

  • Title, mapmaker, year and a link to the original scan
  • The rights statement of the source
  • How you georeferenced it: the tool, the transformation and the number of control points
  • How you extracted the outline: colour selection or hand tracing, and the tolerance you used
  • A plain warning that borders on historical maps were often approximate or disputed

Do not oversell precision

A contour that looks sharp on a screen is still only as accurate as the old map, your control points and the colour boundary. Say so on the page, and let users fade the scan so they can compare for themselves.

Keep modern labels apart from historical shapes

If your map also shows today’s borders, keep them in a separate “Today” layer. On that layer, label Crimea, Donetsk and Luhansk as Ukrainian territory unlawfully occupied by Russia, and do not add modern labels to the historical contours themselves.

🔧 Common Issues and Solutions

Problem: The contour lands in the wrong place

Solution: Check that the GeoTIFF is in EPSG:4326, that the control points were spread over the whole map, and that you did not use borders as control points. Add points where the shift is largest.

Problem: The shape covers the whole map

Solution: The colour match is too loose and the paper is being selected. Look at mask_preview.png and use a stricter --tol, for example 4,15,30.

Problem: The shape has holes or is split into pieces

Solution: Ink lines or fading cut the colour. Loosen --tol, or raise the closing size by editing close_px in the script from 9 to 15.

Problem: The outline looks jagged

Solution: Scan resolution is low or the tolerance is too small. Increase --simplify a little, or smooth the shape later in QGIS with Processing → Smooth.

Problem: The map page is blank or the contour does not appear

Solution: Open the page through python -m http.server, not by double-clicking the file. Press F12 and read the Console for a red error such as a wrong file name.

Problem: The contour appears far away, often near Africa

Solution: Longitude and latitude are swapped. GeoJSON stores longitude first, then latitude. The script does this correctly, so check any coordinates you typed by hand.

Problem: The GeoJSON file is very large

Solution: Raise --simplify, drop small islands with a larger --min-hole and minimum area, or convert to TopoJSON, which is usually several times smaller.

✅

You Now Have a Historical Contour on an Interactive Map

You turned a scanned historical map into data: an outline with real coordinates, a name, a year and a source, shown on a modern interactive map. The same steps work for any region you can separate by colour or trace by hand, and repeating them for several maps lets you compare borders over time.

For an example of historical outlines shown on a modern map, see VICOLEX: Morphing Contour Maps of Ukraine.

About This Tutorial

This guide shows a free workflow for extracting contours from historical maps and placing them on interactive maps, so that libraries, archives and researchers can turn scans into reusable data.

Author: Olha Buchel, PhD in library and information science with a specialization in visualization
Created: December 2026 | Difficulty: Intermediate | Time Required: 2-3 hours

Technologies Used: QGIS, Python (OpenCV, rasterio, GeoPandas, Shapely), GeoJSON, Leaflet, GitHub Pages