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.
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.
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.
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.
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).
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.
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.
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.
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
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.
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.
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 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
The script also writes mask_preview.png. White pixels are the area it picked. Open it next to the map and check three things:
--tol 4,15,30--tol 8,35,60--min-hole pixels--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.

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.
<!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: '© 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
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.
A contour is only useful to other people if they can tell where it came from and how far to trust it.
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.
Keep these facts in the GeoJSON properties or in a README next to it:
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.
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.
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.
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.
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.
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.
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.
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.
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 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.