Using Ordnance Survey Images As Backgrounds In Cartopy

metadata

Previously I have posted about Replacing Cartopy’s Background Image and Adding Background Images Of Elevation (to Cartopy). These two previous efforts were relatively easy because the sets of background images that I was adding were all global, i.e., they were equirectangular images of the whole of the planet. Recently I wanted to have background images in my plots using the following free Ordnance Survey datasets:

This presented a problem because, firstly, the images do not have global extent and, secondly, the images do not use the equirectangular projection. Therefore, they need to be added to a plot using the ax.imshow() method in MatPlotLib with a custom extent and transform, rather than by using the (more user friendly) ax.background_img() method in Cartopy. I decided to write some Python scripts to convert the images into PNG images with sidecar JSON files of their extents (for easy usage later).

The following articles are worth a read too:

Firstly, I wrote the following three Python scripts to save the images contained within the three ZIP files as PNG images and to generate the sidecar JSON files.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

#!/usr/bin/env python3

# Use the proper idiom in the main module ...
# NOTE: See https://docs.python.org/3.11/library/multiprocessing.html#the-spawn-and-forkserver-start-methods
if __name__ == "__main__":
    # NOTE: The following articles are worth a read:
    #         * https://getoutside.ordnancesurvey.co.uk/guides/beginners-guide-to-grid-references/
    #         * https://www.ordnancesurvey.co.uk/documents/resources/guide-coordinate-systems-great-britain.pdf
    # NOTE: I downloaded the "MiniScale" dataset from the Ordnance Survey, see:
    #         * https://www.ordnancesurvey.co.uk/business-government/products/miniscale
    #       This gave me the "minisc_gb.zip" file that is used here.

    # Import standard modules ...
    import io
    import json
    import os
    import zipfile

    # Import special modules ...
    try:
        import PIL
        import PIL.Image
        PIL.Image.MAX_IMAGE_PIXELS = 1024 * 1024 * 1024                         # [px]
        import PIL.TiffTags
    except:
        raise Exception("\"PIL\" is not installed; run \"pip install --user Pillow\"") from None

    # Import my modules ...
    try:
        import pyguymer3
        import pyguymer3.image
    except:
        raise Exception("\"pyguymer3\" is not installed; you need to have the Python module from https://github.com/Guymer/PyGuymer3 located somewhere in your $PYTHONPATH") from None

    # Initialize dictionary ...
    meta = {}

    # Make folders if they are missing ...
    for dname in ["miniscale/colour", "miniscale/greyscale"]:
        if not os.path.exists(dname):
            os.makedirs(dname)

    # Load dataset ...
    with zipfile.ZipFile("minisc_gb.zip", "r") as zObj:
        # Loop over members ...
        for tif in zObj.namelist():
            # Skip this member if it is not a data TIF ...
            if "/RGB_TIF_compressed/" not in tif or not tif.lower().endswith(".tif"):
                continue

            # Extract view name ...
            view = os.path.basename(tif).removesuffix(".tif")

            # Deduce colour and greyscale PNG names ...
            png1 = f"miniscale/colour/{view}.png"
            png2 = f"miniscale/greyscale/{view}.png"

            # Read data TIF into RAM so that it becomes seekable ...
            # NOTE: https://stackoverflow.com/a/12025492
            tObj = io.BytesIO(zObj.read(tif))

            # Open image as RGB (even if it is paletted) ...
            with PIL.Image.open(tObj) as iObj:
                img = iObj.convert("RGB")

            # Loop over data TIF metadata and populate the dictionary with the
            # data TIF's extent ...
            # NOTE: The tie point is the upper-left corner of the data TIF and
            #       Cartopy wants the lower-left corner.
            dx, dy = None, None                                                 # [m/px], [m/px]
            xmin, xmax, ymin, ymax = None, None, None, None                     # [m], [m], [m], [m]
            for key, val in img.tag.items():
                if PIL.TiffTags.TAGS[key] == "ModelPixelScaleTag":
                    dx, dy = val[0], val[1]                                     # [m/px], [m/px]
                if PIL.TiffTags.TAGS[key] == "ModelTiepointTag":
                    xmin, ymax = val[3], val[4]                                 # [m], [m]
            if dx is None or dy is None:
                raise Exception("failed to extract \"ModelPixelScaleTag\"") from None
            if xmin is None or ymax is None:
                raise Exception("failed to extract \"ModelTiepointTag\"") from None
            xmax = xmin + img.size[0] * dx                                      # [m]
            ymin = ymax - img.size[1] * dy                                      # [m]
            meta[view] = {
                   "colour" : png1,
                "greyscale" : png2,
                   "extent" : [xmin, xmax, ymin, ymax],
            }

            # Check if the PNG is missing ...
            if not os.path.exists(png1):
                print(f"Making \"{png1}\" ...")

                # Save PNG ...
                img.save(png1, optimize = True)
                pyguymer3.image.optimize_image(png1, strip = True)

            # Check if the PNG is missing ...
            if not os.path.exists(png2):
                print(f"Making \"{png2}\" ...")

                # Save PNG ...
                img.convert("L").save(png2, optimize = True)
                pyguymer3.image.optimize_image(png2, strip = True)

        # Save JSON ...
        with open("miniscale.json", "wt", encoding = "utf-8") as fObj:
            json.dump(
                meta,
                fObj,
                ensure_ascii = False,
                      indent = 4,
                   sort_keys = True,
            )

              
You may also download “background-OS-images-miniscale.py” directly or view “background-OS-images-miniscale.py” on GitHub Gist (you may need to manually checkout the “main” branch).
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

#!/usr/bin/env python3

# Use the proper idiom in the main module ...
# NOTE: See https://docs.python.org/3.11/library/multiprocessing.html#the-spawn-and-forkserver-start-methods
if __name__ == "__main__":
    # NOTE: The following articles are worth a read:
    #         * https://getoutside.ordnancesurvey.co.uk/guides/beginners-guide-to-grid-references/
    #         * https://www.ordnancesurvey.co.uk/documents/resources/guide-coordinate-systems-great-britain.pdf
    # NOTE: I downloaded the "GB Overview Maps" dataset from the Ordnance
    #       Survey, see:
    #         * https://www.ordnancesurvey.co.uk/business-government/products/gb-overview
    #       This gave me the "Over_gb.zip" file that is used here.

    # Import standard modules ...
    import io
    import json
    import os
    import zipfile

    # Import special modules ...
    try:
        import PIL
        import PIL.Image
        PIL.Image.MAX_IMAGE_PIXELS = 1024 * 1024 * 1024                         # [px]
        import PIL.TiffTags
    except:
        raise Exception("\"PIL\" is not installed; run \"pip install --user Pillow\"") from None

    # Import my modules ...
    try:
        import pyguymer3
        import pyguymer3.image
    except:
        raise Exception("\"pyguymer3\" is not installed; you need to have the Python module from https://github.com/Guymer/PyGuymer3 located somewhere in your $PYTHONPATH") from None

    # Initialize dictionary ...
    meta = {}

    # Make folders if they are missing ...
    for dname in ["overview/colour", "overview/greyscale"]:
        if not os.path.exists(dname):
            os.makedirs(dname)

    # Load dataset ...
    with zipfile.ZipFile("Over_gb.zip", "r") as zObj:
        # Loop over members ...
        for tif in zObj.namelist():
            # Skip this member if it is not a data TIF ...
            if not tif.lower().endswith(".tif"):
                continue

            # Extract view name ...
            view = os.path.basename(tif).removesuffix(".tif")

            # Deduce colour and greyscale PNG names ...
            png1 = f"overview/colour/{view}.png"
            png2 = f"overview/greyscale/{view}.png"

            # Read data TIF into RAM so that it becomes seekable ...
            # NOTE: https://stackoverflow.com/a/12025492
            tObj = io.BytesIO(zObj.read(tif))

            # Open image as RGB (even if it is paletted) ...
            with PIL.Image.open(tObj) as iObj:
                img = iObj.convert("RGB")

            # Loop over data TIF metadata and populate the dictionary with the
            # data TIF's extent ...
            # NOTE: The tie point is the upper-left corner of the data TIF and
            #       Cartopy wants the lower-left corner.
            dx, dy = None, None                                                 # [m/px], [m/px]
            xmin, xmax, ymin, ymax = None, None, None, None                     # [m], [m], [m], [m]
            for key, val in img.tag.items():
                if PIL.TiffTags.TAGS[key] == "ModelPixelScaleTag":
                    dx, dy = val[0], val[1]                                     # [m/px], [m/px]
                if PIL.TiffTags.TAGS[key] == "ModelTiepointTag":
                    xmin, ymax = val[3], val[4]                                 # [m], [m]
            if dx is None or dy is None:
                raise Exception("failed to extract \"ModelPixelScaleTag\"") from None
            if xmin is None or ymax is None:
                raise Exception("failed to extract \"ModelTiepointTag\"") from None
            xmax = xmin + img.size[0] * dx                                      # [m]
            ymin = ymax - img.size[1] * dy                                      # [m]
            meta[view] = {
                   "colour" : png1,
                "greyscale" : png2,
                   "extent" : [xmin, xmax, ymin, ymax],
            }

            # Check if the PNG is missing ...
            if not os.path.exists(png1):
                print(f"Making \"{png1}\" ...")

                # Save PNG ...
                img.save(png1, optimize = True)
                pyguymer3.image.optimize_image(png1, strip = True)

            # Check if the PNG is missing ...
            if not os.path.exists(png2):
                print(f"Making \"{png2}\" ...")

                # Save PNG ...
                img.convert("L").save(png2, optimize = True)
                pyguymer3.image.optimize_image(png2, strip = True)

        # Save JSON ...
        with open("overview.json", "wt", encoding = "utf-8") as fObj:
            json.dump(
                meta,
                fObj,
                ensure_ascii = False,
                      indent = 4,
                   sort_keys = True,
            )

              
You may also download “background-OS-images-overview.py” directly or view “background-OS-images-overview.py” on GitHub Gist (you may need to manually checkout the “main” branch).
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

#!/usr/bin/env python3

# Use the proper idiom in the main module ...
# NOTE: See https://docs.python.org/3.11/library/multiprocessing.html#the-spawn-and-forkserver-start-methods
if __name__ == "__main__":
    # NOTE: The following articles are worth a read:
    #         * https://getoutside.ordnancesurvey.co.uk/guides/beginners-guide-to-grid-references/
    #         * https://www.ordnancesurvey.co.uk/documents/resources/guide-coordinate-systems-great-britain.pdf
    # NOTE: I downloaded the "1:250,000 Scale Colour Raster" dataset from the
    #       Ordnance Survey, see:
    #         * https://www.ordnancesurvey.co.uk/business-government/products/250k-raster
    #       This gave me the "ras250_gb.zip" file that is used here.

    # Import standard modules ...
    import io
    import json
    import os
    import zipfile

    # Import special modules ...
    try:
        import PIL
        import PIL.Image
        PIL.Image.MAX_IMAGE_PIXELS = 1024 * 1024 * 1024                         # [px]
        import PIL.TiffTags
    except:
        raise Exception("\"PIL\" is not installed; run \"pip install --user Pillow\"") from None

    # Import my modules ...
    try:
        import pyguymer3
        import pyguymer3.image
    except:
        raise Exception("\"pyguymer3\" is not installed; you need to have the Python module from https://github.com/Guymer/PyGuymer3 located somewhere in your $PYTHONPATH") from None

    # Initialize dictionary ...
    meta = {}

    # Make folders if they are missing ...
    for dname in ["raster/colour", "raster/greyscale"]:
        if not os.path.exists(dname):
            os.makedirs(dname)

    # Load dataset ...
    with zipfile.ZipFile("ras250_gb.zip", "r") as zObj:
        # Loop over members ...
        for tif in zObj.namelist():
            # Skip this member if it is not a data TIF ...
            if "/data/" not in tif or not tif.lower().endswith(".tif"):
                continue

            # Extract tile name ...
            tile = os.path.basename(tif).removesuffix(".tif")

            # Deduce colour and greyscale PNG names ...
            png1 = f"raster/colour/{tile}.png"
            png2 = f"raster/greyscale/{tile}.png"

            # Read data TIF into RAM so that it becomes seekable ...
            # NOTE: https://stackoverflow.com/a/12025492
            tObj = io.BytesIO(zObj.read(tif))

            # Open image as RGB (even if it is paletted) ...
            with PIL.Image.open(tObj) as iObj:
                img = iObj.convert("RGB")

            # Loop over data TIF metadata and populate the dictionary with the
            # data TIF's extent ...
            # NOTE: The tie point is the upper-left corner of the data TIF and
            #       Cartopy wants the lower-left corner.
            dx, dy = None, None                                                 # [m/px], [m/px]
            xmin, xmax, ymin, ymax = None, None, None, None                     # [m], [m], [m], [m]
            for key, val in img.tag.items():
                if PIL.TiffTags.TAGS[key] == "ModelPixelScaleTag":
                    dx, dy = val[0], val[1]                                     # [m/px], [m/px]
                if PIL.TiffTags.TAGS[key] == "ModelTiepointTag":
                    xmin, ymax = val[3], val[4]                                 # [m], [m]
            if dx is None or dy is None:
                raise Exception("failed to extract \"ModelPixelScaleTag\"") from None
            if xmin is None or ymax is None:
                raise Exception("failed to extract \"ModelTiepointTag\"") from None
            xmax = xmin + img.size[0] * dx                                      # [m]
            ymin = ymax - img.size[1] * dy                                      # [m]
            meta[tile] = {
                   "colour" : png1,
                "greyscale" : png2,
                   "extent" : [xmin, xmax, ymin, ymax],
            }

            # Check if the PNG is missing ...
            if not os.path.exists(png1):
                print(f"Making \"{png1}\" ...")

                # Save PNG ...
                img.save(png1, optimize = True)
                pyguymer3.image.optimize_image(png1, strip = True)

            # Check if the PNG is missing ...
            if not os.path.exists(png2):
                print(f"Making \"{png2}\" ...")

                # Save PNG ...
                img.convert("L").save(png2, optimize = True)
                pyguymer3.image.optimize_image(png2, strip = True)

        # Save JSON ...
        with open("raster.json", "wt", encoding = "utf-8") as fObj:
            json.dump(
                meta,
                fObj,
                ensure_ascii = False,
                      indent = 4,
                   sort_keys = True,
            )

              
You may also download “background-OS-images-raster.py” directly or view “background-OS-images-raster.py” on GitHub Gist (you may need to manually checkout the “main” branch).

These are the three sidecar JSON files that were generated. The JSON files are very simple: they just give the name of the colour PNG image, the name of the greyscale PNG image and the extent of the PNG images on the Ordnance Survey National Grid.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

{
    "MiniScale_(mono)_R22": {
        "colour": "miniscale/colour/MiniScale_(mono)_R22.png",
        "extent": [
            0.0,
            700000.0000027993,
            0.0,
            1300000.0000052003
        ],
        "greyscale": "miniscale/greyscale/MiniScale_(mono)_R22.png"
    },
    "MiniScale_(relief1)_R22": {
        "colour": "miniscale/colour/MiniScale_(relief1)_R22.png",
        "extent": [
            0.0,
            700000.0000027993,
            0.0,
            1300000.0000052003
        ],
        "greyscale": "miniscale/greyscale/MiniScale_(relief1)_R22.png"
    },
    "MiniScale_(relief2)_R22": {
        "colour": "miniscale/colour/MiniScale_(relief2)_R22.png",
        "extent": [
            0.0,
            700000.0000027993,
            0.0,
            1300000.0000052003
        ],
        "greyscale": "miniscale/greyscale/MiniScale_(relief2)_R22.png"
    },
    "MiniScale_(standard)_R22": {
        "colour": "miniscale/colour/MiniScale_(standard)_R22.png",
        "extent": [
            0.0,
            700000.0000027993,
            0.0,
            1300000.0000052003
        ],
        "greyscale": "miniscale/greyscale/MiniScale_(standard)_R22.png"
    },
    "MiniScale_(std_with_grid)_R22": {
        "colour": "miniscale/colour/MiniScale_(std_with_grid)_R22.png",
        "extent": [
            0.0,
            700000.0000027993,
            0.0,
            1300000.0000052003
        ],
        "greyscale": "miniscale/greyscale/MiniScale_(std_with_grid)_R22.png"
    }
}

              
You may also download “miniscale.json” directly or view “miniscale.json” on GitHub Gist (you may need to manually checkout the “main” branch).
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22

{
    "GBOverview": {
        "colour": "overview/colour/GBOverview.png",
        "extent": [
            -649749.9999999999,
            1350250.0,
            -150250.0,
            1449750.0000000005
        ],
        "greyscale": "overview/greyscale/GBOverview.png"
    },
    "GBOverviewPlus": {
        "colour": "overview/colour/GBOverviewPlus.png",
        "extent": [
            -649749.9999999999,
            1350250.0,
            -150250.0,
            1449750.0000000005
        ],
        "greyscale": "overview/greyscale/GBOverviewPlus.png"
    }
}

              
You may also download “overview.json” directly or view “overview.json” on GitHub Gist (you may need to manually checkout the “main” branch).
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562

{
    "HP": {
        "colour": "raster/colour/HP.png",
        "extent": [
            400000.0,
            500000.0,
            1200000.0,
            1300000.0
        ],
        "greyscale": "raster/greyscale/HP.png"
    },
    "HT": {
        "colour": "raster/colour/HT.png",
        "extent": [
            300000.0,
            400000.0,
            1100000.0,
            1200000.0
        ],
        "greyscale": "raster/greyscale/HT.png"
    },
    "HU": {
        "colour": "raster/colour/HU.png",
        "extent": [
            400000.0,
            500000.0,
            1100000.0,
            1200000.0
        ],
        "greyscale": "raster/greyscale/HU.png"
    },
    "HW": {
        "colour": "raster/colour/HW.png",
        "extent": [
            100000.0,
            200000.0,
            1000000.0,
            1100000.0
        ],
        "greyscale": "raster/greyscale/HW.png"
    },
    "HX": {
        "colour": "raster/colour/HX.png",
        "extent": [
            200000.0,
            300000.0,
            1000000.0,
            1100000.0
        ],
        "greyscale": "raster/greyscale/HX.png"
    },
    "HY": {
        "colour": "raster/colour/HY.png",
        "extent": [
            300000.0,
            400000.0,
            1000000.0,
            1100000.0
        ],
        "greyscale": "raster/greyscale/HY.png"
    },
    "HZ": {
        "colour": "raster/colour/HZ.png",
        "extent": [
            400000.0,
            500000.0,
            1000000.0,
            1100000.0
        ],
        "greyscale": "raster/greyscale/HZ.png"
    },
    "NA": {
        "colour": "raster/colour/NA.png",
        "extent": [
            0.0,
            100000.0,
            900000.0,
            1000000.0
        ],
        "greyscale": "raster/greyscale/NA.png"
    },
    "NB": {
        "colour": "raster/colour/NB.png",
        "extent": [
            100000.0,
            200000.0,
            900000.0,
            1000000.0
        ],
        "greyscale": "raster/greyscale/NB.png"
    },
    "NC": {
        "colour": "raster/colour/NC.png",
        "extent": [
            200000.0,
            300000.0,
            900000.0,
            1000000.0
        ],
        "greyscale": "raster/greyscale/NC.png"
    },
    "ND": {
        "colour": "raster/colour/ND.png",
        "extent": [
            300000.0,
            400000.0,
            900000.0,
            1000000.0
        ],
        "greyscale": "raster/greyscale/ND.png"
    },
    "NF": {
        "colour": "raster/colour/NF.png",
        "extent": [
            0.0,
            100000.0,
            800000.0,
            900000.0
        ],
        "greyscale": "raster/greyscale/NF.png"
    },
    "NG": {
        "colour": "raster/colour/NG.png",
        "extent": [
            100000.0,
            200000.0,
            800000.0,
            900000.0
        ],
        "greyscale": "raster/greyscale/NG.png"
    },
    "NH": {
        "colour": "raster/colour/NH.png",
        "extent": [
            200000.0,
            300000.0,
            800000.0,
            900000.0
        ],
        "greyscale": "raster/greyscale/NH.png"
    },
    "NJ": {
        "colour": "raster/colour/NJ.png",
        "extent": [
            300000.0,
            400000.0,
            800000.0,
            900000.0
        ],
        "greyscale": "raster/greyscale/NJ.png"
    },
    "NK": {
        "colour": "raster/colour/NK.png",
        "extent": [
            400000.0,
            500000.0,
            800000.0,
            900000.0
        ],
        "greyscale": "raster/greyscale/NK.png"
    },
    "NL": {
        "colour": "raster/colour/NL.png",
        "extent": [
            0.0,
            100000.0,
            700000.0,
            800000.0
        ],
        "greyscale": "raster/greyscale/NL.png"
    },
    "NM": {
        "colour": "raster/colour/NM.png",
        "extent": [
            100000.0,
            200000.0,
            700000.0,
            800000.0
        ],
        "greyscale": "raster/greyscale/NM.png"
    },
    "NN": {
        "colour": "raster/colour/NN.png",
        "extent": [
            200000.0,
            300000.0,
            700000.0,
            800000.0
        ],
        "greyscale": "raster/greyscale/NN.png"
    },
    "NO": {
        "colour": "raster/colour/NO.png",
        "extent": [
            300000.0,
            400000.0,
            700000.0,
            800000.0
        ],
        "greyscale": "raster/greyscale/NO.png"
    },
    "NR": {
        "colour": "raster/colour/NR.png",
        "extent": [
            100000.0,
            200000.0,
            600000.0,
            700000.0
        ],
        "greyscale": "raster/greyscale/NR.png"
    },
    "NS": {
        "colour": "raster/colour/NS.png",
        "extent": [
            200000.0,
            300000.0,
            600000.0,
            700000.0
        ],
        "greyscale": "raster/greyscale/NS.png"
    },
    "NT": {
        "colour": "raster/colour/NT.png",
        "extent": [
            300000.0,
            400000.0,
            600000.0,
            700000.0
        ],
        "greyscale": "raster/greyscale/NT.png"
    },
    "NU": {
        "colour": "raster/colour/NU.png",
        "extent": [
            400000.0,
            500000.0,
            600000.0,
            700000.0
        ],
        "greyscale": "raster/greyscale/NU.png"
    },
    "NW": {
        "colour": "raster/colour/NW.png",
        "extent": [
            100000.0,
            200000.0,
            500000.0,
            600000.0
        ],
        "greyscale": "raster/greyscale/NW.png"
    },
    "NX": {
        "colour": "raster/colour/NX.png",
        "extent": [
            200000.0,
            300000.0,
            500000.0,
            600000.0
        ],
        "greyscale": "raster/greyscale/NX.png"
    },
    "NY": {
        "colour": "raster/colour/NY.png",
        "extent": [
            300000.0,
            400000.0,
            500000.0,
            600000.0
        ],
        "greyscale": "raster/greyscale/NY.png"
    },
    "NZ": {
        "colour": "raster/colour/NZ.png",
        "extent": [
            400000.0,
            500000.0,
            500000.0,
            600000.0
        ],
        "greyscale": "raster/greyscale/NZ.png"
    },
    "OV": {
        "colour": "raster/colour/OV.png",
        "extent": [
            500000.0,
            600000.0,
            500000.0,
            600000.0
        ],
        "greyscale": "raster/greyscale/OV.png"
    },
    "SC": {
        "colour": "raster/colour/SC.png",
        "extent": [
            200000.0,
            300000.0,
            400000.0,
            500000.0
        ],
        "greyscale": "raster/greyscale/SC.png"
    },
    "SD": {
        "colour": "raster/colour/SD.png",
        "extent": [
            300000.0,
            400000.0,
            400000.0,
            500000.0
        ],
        "greyscale": "raster/greyscale/SD.png"
    },
    "SE": {
        "colour": "raster/colour/SE.png",
        "extent": [
            400000.0,
            500000.0,
            400000.0,
            500000.0
        ],
        "greyscale": "raster/greyscale/SE.png"
    },
    "SH": {
        "colour": "raster/colour/SH.png",
        "extent": [
            200000.0,
            300000.0,
            300000.0,
            400000.0
        ],
        "greyscale": "raster/greyscale/SH.png"
    },
    "SJ": {
        "colour": "raster/colour/SJ.png",
        "extent": [
            300000.0,
            400000.0,
            300000.0,
            400000.0
        ],
        "greyscale": "raster/greyscale/SJ.png"
    },
    "SK": {
        "colour": "raster/colour/SK.png",
        "extent": [
            400000.0,
            500000.0,
            300000.0,
            400000.0
        ],
        "greyscale": "raster/greyscale/SK.png"
    },
    "SM": {
        "colour": "raster/colour/SM.png",
        "extent": [
            100000.0,
            200000.0,
            200000.0,
            300000.0
        ],
        "greyscale": "raster/greyscale/SM.png"
    },
    "SN": {
        "colour": "raster/colour/SN.png",
        "extent": [
            200000.0,
            300000.0,
            200000.0,
            300000.0
        ],
        "greyscale": "raster/greyscale/SN.png"
    },
    "SO": {
        "colour": "raster/colour/SO.png",
        "extent": [
            300000.0,
            400000.0,
            200000.0,
            300000.0
        ],
        "greyscale": "raster/greyscale/SO.png"
    },
    "SP": {
        "colour": "raster/colour/SP.png",
        "extent": [
            400000.0,
            500000.0,
            200000.0,
            300000.0
        ],
        "greyscale": "raster/greyscale/SP.png"
    },
    "SR": {
        "colour": "raster/colour/SR.png",
        "extent": [
            100000.0,
            200000.0,
            100000.0,
            200000.0
        ],
        "greyscale": "raster/greyscale/SR.png"
    },
    "SS": {
        "colour": "raster/colour/SS.png",
        "extent": [
            200000.0,
            300000.0,
            100000.0,
            200000.0
        ],
        "greyscale": "raster/greyscale/SS.png"
    },
    "ST": {
        "colour": "raster/colour/ST.png",
        "extent": [
            300000.0,
            400000.0,
            100000.0,
            200000.0
        ],
        "greyscale": "raster/greyscale/ST.png"
    },
    "SU": {
        "colour": "raster/colour/SU.png",
        "extent": [
            400000.0,
            500000.0,
            100000.0,
            200000.0
        ],
        "greyscale": "raster/greyscale/SU.png"
    },
    "SV": {
        "colour": "raster/colour/SV.png",
        "extent": [
            0.0,
            100000.0,
            0.0,
            100000.0
        ],
        "greyscale": "raster/greyscale/SV.png"
    },
    "SW": {
        "colour": "raster/colour/SW.png",
        "extent": [
            100000.0,
            200000.0,
            0.0,
            100000.0
        ],
        "greyscale": "raster/greyscale/SW.png"
    },
    "SX": {
        "colour": "raster/colour/SX.png",
        "extent": [
            200000.0,
            300000.0,
            0.0,
            100000.0
        ],
        "greyscale": "raster/greyscale/SX.png"
    },
    "SY": {
        "colour": "raster/colour/SY.png",
        "extent": [
            300000.0,
            400000.0,
            0.0,
            100000.0
        ],
        "greyscale": "raster/greyscale/SY.png"
    },
    "SZ": {
        "colour": "raster/colour/SZ.png",
        "extent": [
            400000.0,
            500000.0,
            0.0,
            100000.0
        ],
        "greyscale": "raster/greyscale/SZ.png"
    },
    "TA": {
        "colour": "raster/colour/TA.png",
        "extent": [
            500000.0,
            600000.0,
            400000.0,
            500000.0
        ],
        "greyscale": "raster/greyscale/TA.png"
    },
    "TF": {
        "colour": "raster/colour/TF.png",
        "extent": [
            500000.0,
            600000.0,
            300000.0,
            400000.0
        ],
        "greyscale": "raster/greyscale/TF.png"
    },
    "TG": {
        "colour": "raster/colour/TG.png",
        "extent": [
            600000.0,
            700000.0,
            300000.0,
            400000.0
        ],
        "greyscale": "raster/greyscale/TG.png"
    },
    "TL": {
        "colour": "raster/colour/TL.png",
        "extent": [
            500000.0,
            600000.0,
            200000.0,
            300000.0
        ],
        "greyscale": "raster/greyscale/TL.png"
    },
    "TM": {
        "colour": "raster/colour/TM.png",
        "extent": [
            600000.0,
            700000.0,
            200000.0,
            300000.0
        ],
        "greyscale": "raster/greyscale/TM.png"
    },
    "TQ": {
        "colour": "raster/colour/TQ.png",
        "extent": [
            500000.0,
            600000.0,
            100000.0,
            200000.0
        ],
        "greyscale": "raster/greyscale/TQ.png"
    },
    "TR": {
        "colour": "raster/colour/TR.png",
        "extent": [
            600000.0,
            700000.0,
            100000.0,
            200000.0
        ],
        "greyscale": "raster/greyscale/TR.png"
    },
    "TV": {
        "colour": "raster/colour/TV.png",
        "extent": [
            500000.0,
            600000.0,
            0.0,
            100000.0
        ],
        "greyscale": "raster/greyscale/TV.png"
    }
}

              
You may also download “raster.json” directly or view “raster.json” on GitHub Gist (you may need to manually checkout the “main” branch).

Secondly, as a demonstration of how to use these generated PNG images and JSON files, I wrote the following three Python scripts to make an example plot for each free Ordnance Survey dataset.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

#!/usr/bin/env python3

# Use the proper idiom in the main module ...
# NOTE: See https://docs.python.org/3.11/library/multiprocessing.html#the-spawn-and-forkserver-start-methods
if __name__ == "__main__":
    # Import standard modules ...
    import json
    import os

    # Import special modules ...
    try:
        import cartopy
        cartopy.config.update(
            {
                "cache_dir" : os.path.expanduser("~/.local/share/cartopy_cache"),
            }
        )
    except:
        raise Exception("\"cartopy\" is not installed; run \"pip install --user Cartopy\"") from None
    try:
        import matplotlib
        matplotlib.rcParams.update(
            {
                       "backend" : "Agg",                                       # NOTE: See https://matplotlib.org/stable/gallery/user_interfaces/canvasagg.html
                    "figure.dpi" : 300,
                "figure.figsize" : (9.6, 7.2),                                  # NOTE: See https://github.com/Guymer/misc/blob/main/README.md#matplotlib-figure-sizes
                     "font.size" : 8,
            }
        )
        import matplotlib.pyplot
    except:
        raise Exception("\"matplotlib\" is not installed; run \"pip install --user matplotlib\"") from None
    try:
        import shapely
        import shapely.geometry
    except:
        raise Exception("\"shapely\" is not installed; run \"pip install --user Shapely\"") from None

    # Import my modules ...
    try:
        import pyguymer3
        import pyguymer3.geo
        import pyguymer3.image
    except:
        raise Exception("\"pyguymer3\" is not installed; you need to have the Python module from https://github.com/Guymer/PyGuymer3 located somewhere in your $PYTHONPATH") from None

    # Set point ...
    point = (-1.463097, 52.915709)                                              # [°], [°]

    # Set number of bearings ...
    nang = 361                                                                  # [#]

    # Create short-hand for the colour map ...
    cmap = matplotlib.pyplot.get_cmap("jet")

    # Load tile metadata ...
    with open("OrdnanceSurveyBackgroundImages/miniscale.json", "rt", encoding = "utf-8") as fObj:
        meta = json.load(fObj)

    # **************************************************************************

    # Create figure ...
    fg = matplotlib.pyplot.figure(figsize = (7.2, 7.2))

    # Create axis ...
    ax = pyguymer3.geo.add_axis(
        fg,
        dist = 20.0e3,
         lat = point[1],
         lon = point[0],
    )

    # Configure axis ...
    ax.set_title("Derby Train Station")

    # Initialize float and lists and draw data ...
    # NOTE: As of 5/Dec/2023, the default "zorder" of the coastlines is 1.5, the
    #       default "zorder" of the gridlines is 2.0 and the default "zorder" of
    #       the scattered points is 1.0.
    dist = 0.0                                                                  # [m]
    labels = []
    lines = []
    ax.scatter(
        [point[0]],
        [point[1]],
            alpha = 1.0,
        edgecolor = "none",
        facecolor = "red",
        transform = cartopy.crs.PlateCarree(),
           zorder = 5.0,
    )
    for i in range(6):
        dist += 2500.0                                                          # [m]
        ax.add_geometries(
            [pyguymer3.geo.buffer(shapely.geometry.Point(point[0], point[1]), dist, debug = False, nang = nang, simp = -1.0)],
            cartopy.crs.PlateCarree(),
            alpha = 1.0,
            edgecolor = cmap(float(i) / 5.0),
            facecolor = "none",
            linewidth = 1.0
        )
        labels.append(f"{0.001 * dist:.1f} km")
        lines.append(matplotlib.lines.Line2D([], [], color = cmap(float(i) / 5.0)))

    # Draw background image ...
    ax.imshow(
        matplotlib.pyplot.imread(f'OrdnanceSurveyBackgroundImages/{meta["MiniScale_(mono)_R22"]["greyscale"]}'),
                 cmap = "gray",
               extent = meta["MiniScale_(mono)_R22"]["extent"],
        interpolation = "bicubic",
               origin = "upper",
            transform = cartopy.crs.OSGB(),
                 vmin = 0.0,
                 vmax = 1.0,
    )

    # Configure axis ...
    ax.legend(
        lines,
        labels,
         loc = "upper right",
        ncol = 1,
    )

    # Configure figure ...
    fg.tight_layout()

    # Save figure ...
    fg.savefig("miniscale.png")
    matplotlib.pyplot.close(fg)

    # Optimize PNG ...
    pyguymer3.image.optimize_image("miniscale.png", strip = True)

              
You may also download “example-background-OS-image-miniscale.py” directly or view “example-background-OS-image-miniscale.py” on GitHub Gist (you may need to manually checkout the “main” branch).
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

#!/usr/bin/env python3

# Use the proper idiom in the main module ...
# NOTE: See https://docs.python.org/3.11/library/multiprocessing.html#the-spawn-and-forkserver-start-methods
if __name__ == "__main__":
    # Import standard modules ...
    import json
    import os

    # Import special modules ...
    try:
        import cartopy
        cartopy.config.update(
            {
                "cache_dir" : os.path.expanduser("~/.local/share/cartopy_cache"),
            }
        )
    except:
        raise Exception("\"cartopy\" is not installed; run \"pip install --user Cartopy\"") from None
    try:
        import matplotlib
        matplotlib.rcParams.update(
            {
                       "backend" : "Agg",                                       # NOTE: See https://matplotlib.org/stable/gallery/user_interfaces/canvasagg.html
                    "figure.dpi" : 300,
                "figure.figsize" : (9.6, 7.2),                                  # NOTE: See https://github.com/Guymer/misc/blob/main/README.md#matplotlib-figure-sizes
                     "font.size" : 8,
            }
        )
        import matplotlib.pyplot
    except:
        raise Exception("\"matplotlib\" is not installed; run \"pip install --user matplotlib\"") from None
    try:
        import shapely
        import shapely.geometry
    except:
        raise Exception("\"shapely\" is not installed; run \"pip install --user Shapely\"") from None

    # Import my modules ...
    try:
        import pyguymer3
        import pyguymer3.geo
        import pyguymer3.image
    except:
        raise Exception("\"pyguymer3\" is not installed; you need to have the Python module from https://github.com/Guymer/PyGuymer3 located somewhere in your $PYTHONPATH") from None

    # Set point ...
    point = (-1.463097, 52.915709)                                              # [°], [°]

    # Set number of bearings ...
    nang = 361                                                                  # [#]

    # Create short-hand for the colour map ...
    cmap = matplotlib.pyplot.get_cmap("jet")

    # Load tile metadata ...
    with open("OrdnanceSurveyBackgroundImages/overview.json", "rt", encoding = "utf-8") as fObj:
        meta = json.load(fObj)

    # **************************************************************************

    # Create figure ...
    fg = matplotlib.pyplot.figure(figsize = (7.2, 7.2))

    # Create axis ...
    ax = pyguymer3.geo.add_axis(
        fg,
        dist = 20.0e3,
         lat = point[1],
         lon = point[0],
    )

    # Configure axis ...
    ax.set_title("Derby Train Station")

    # Initialize float and lists and draw data ...
    # NOTE: As of 5/Dec/2023, the default "zorder" of the coastlines is 1.5, the
    #       default "zorder" of the gridlines is 2.0 and the default "zorder" of
    #       the scattered points is 1.0.
    dist = 0.0                                                                  # [m]
    labels = []
    lines = []
    ax.scatter(
        [point[0]],
        [point[1]],
            alpha = 1.0,
        edgecolor = "none",
        facecolor = "red",
        transform = cartopy.crs.PlateCarree(),
           zorder = 5.0,
    )
    for i in range(6):
        dist += 2500.0                                                          # [m]
        ax.add_geometries(
            [pyguymer3.geo.buffer(shapely.geometry.Point(point[0], point[1]), dist, debug = False, nang = nang, simp = -1.0)],
            cartopy.crs.PlateCarree(),
            alpha = 1.0,
            edgecolor = cmap(float(i) / 5.0),
            facecolor = "none",
            linewidth = 1.0
        )
        labels.append(f"{0.001 * dist:.1f} km")
        lines.append(matplotlib.lines.Line2D([], [], color = cmap(float(i) / 5.0)))

    # Draw background image ...
    ax.imshow(
        matplotlib.pyplot.imread(f'OrdnanceSurveyBackgroundImages/{meta["GBOverviewPlus"]["greyscale"]}'),
                 cmap = "gray",
               extent = meta["GBOverviewPlus"]["extent"],
        interpolation = "bicubic",
               origin = "upper",
            transform = cartopy.crs.OSGB(),
                 vmin = 0.0,
                 vmax = 1.0,
    )

    # Configure axis ... ...
    ax.legend(
        lines,
        labels,
         loc = "upper right",
        ncol = 1,
    )

    # Configure figure ...
    fg.tight_layout()

    # Save figure ...
    fg.savefig("overview.png")
    matplotlib.pyplot.close(fg)

    # Optimize PNG ...
    pyguymer3.image.optimize_image("overview.png", strip = True)

              
You may also download “example-background-OS-image-overview.py” directly or view “example-background-OS-image-overview.py” on GitHub Gist (you may need to manually checkout the “main” branch).
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

#!/usr/bin/env python3

# Use the proper idiom in the main module ...
# NOTE: See https://docs.python.org/3.11/library/multiprocessing.html#the-spawn-and-forkserver-start-methods
if __name__ == "__main__":
    # Import standard modules ...
    import json
    import os

    # Import special modules ...
    try:
        import cartopy
        cartopy.config.update(
            {
                "cache_dir" : os.path.expanduser("~/.local/share/cartopy_cache"),
            }
        )
    except:
        raise Exception("\"cartopy\" is not installed; run \"pip install --user Cartopy\"") from None
    try:
        import matplotlib
        matplotlib.rcParams.update(
            {
                       "backend" : "Agg",                                       # NOTE: See https://matplotlib.org/stable/gallery/user_interfaces/canvasagg.html
                    "figure.dpi" : 300,
                "figure.figsize" : (9.6, 7.2),                                  # NOTE: See https://github.com/Guymer/misc/blob/main/README.md#matplotlib-figure-sizes
                     "font.size" : 8,
            }
        )
        import matplotlib.pyplot
    except:
        raise Exception("\"matplotlib\" is not installed; run \"pip install --user matplotlib\"") from None
    try:
        import shapely
        import shapely.geometry
    except:
        raise Exception("\"shapely\" is not installed; run \"pip install --user Shapely\"") from None

    # Import my modules ...
    try:
        import pyguymer3
        import pyguymer3.geo
        import pyguymer3.image
    except:
        raise Exception("\"pyguymer3\" is not installed; you need to have the Python module from https://github.com/Guymer/PyGuymer3 located somewhere in your $PYTHONPATH") from None

    # Set point ...
    point = (-1.463097, 52.915709)                                              # [°], [°]

    # Set number of bearings ...
    nang = 361                                                                  # [#]

    # Create short-hand for the colour map ...
    cmap = matplotlib.pyplot.get_cmap("jet")

    # Load tile metadata ...
    with open("OrdnanceSurveyBackgroundImages/raster.json", "rt", encoding = "utf-8") as fObj:
        meta = json.load(fObj)

    # **************************************************************************

    # Create figure ...
    fg = matplotlib.pyplot.figure(figsize = (7.2, 7.2))

    # Create axis ...
    ax = pyguymer3.geo.add_axis(
        fg,
        dist = 20.0e3,
         lat = point[1],
         lon = point[0],
    )

    # Configure axis ...
    ax.set_title("Derby Train Station")

    # Initialize float and lists and draw data ...
    # NOTE: As of 5/Dec/2023, the default "zorder" of the coastlines is 1.5, the
    #       default "zorder" of the gridlines is 2.0 and the default "zorder" of
    #       the scattered points is 1.0.
    dist = 0.0                                                                  # [m]
    labels = []
    lines = []
    ax.scatter(
        [point[0]],
        [point[1]],
            alpha = 1.0,
        edgecolor = "none",
        facecolor = "red",
        transform = cartopy.crs.PlateCarree(),
           zorder = 5.0,
    )
    for i in range(6):
        dist += 2500.0                                                          # [m]
        ax.add_geometries(
            [pyguymer3.geo.buffer(shapely.geometry.Point(point[0], point[1]), dist, debug = False, nang = nang, simp = -1.0)],
            cartopy.crs.PlateCarree(),
            alpha = 1.0,
            edgecolor = cmap(float(i) / 5.0),
            facecolor = "none",
            linewidth = 1.0
        )
        labels.append(f"{0.001 * dist:.1f} km")
        lines.append(matplotlib.lines.Line2D([], [], color = cmap(float(i) / 5.0)))

    # Draw background image ...
    ax.imshow(
        matplotlib.pyplot.imread(f'OrdnanceSurveyBackgroundImages/{meta["SK"]["greyscale"]}'),
                 cmap = "gray",
               extent = meta["SK"]["extent"],
        interpolation = "bicubic",
               origin = "upper",
            transform = cartopy.crs.OSGB(),
                 vmin = 0.0,
                 vmax = 1.0,
    )

    # Configure axis ...
    ax.legend(
        lines,
        labels,
         loc = "upper right",
        ncol = 1,
    )

    # Configure figure ...
    fg.tight_layout()

    # Save figure ...
    fg.savefig("raster.png")
    matplotlib.pyplot.close(fg)

    # Optimize PNG ...
    pyguymer3.image.optimize_image("raster.png", strip = True)

              
You may also download “example-background-OS-image-raster.py” directly or view “example-background-OS-image-raster.py” on GitHub Gist (you may need to manually checkout the “main” branch).

Below are the three example plots (showing radii around Derby Train Station) using the three free Ordnance Survey datasets.

Download:
  1. 512 px × 512 px (0.3 Mpx; 213.1 KiB)
  2. 1,024 px × 1,024 px (1.0 Mpx; 541.5 KiB)
  3. 2,048 px × 2,048 px (4.2 Mpx; 1.4 MiB)
  4. 2,160 px × 2,160 px (4.7 Mpx; 1.3 MiB)
Download:
  1. 512 px × 512 px (0.3 Mpx; 104.4 KiB)
  2. 1,024 px × 1,024 px (1.0 Mpx; 226.7 KiB)
  3. 2,048 px × 2,048 px (4.2 Mpx; 553.6 KiB)
  4. 2,160 px × 2,160 px (4.7 Mpx; 410.6 KiB)
Download:
  1. 512 px × 512 px (0.3 Mpx; 338.8 KiB)
  2. 1,024 px × 1,024 px (1.0 Mpx; 1.0 MiB)
  3. 2,048 px × 2,048 px (4.2 Mpx; 2.8 MiB)
  4. 2,160 px × 2,160 px (4.7 Mpx; 2.8 MiB)

I believe that the above examples (using the ax.imshow() method) are not too onerous for the user and I hope that this little project means that I will be using more relevant background images in some of my plots in future.