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
114
115
116
117
118
119
120
121
122

#!/usr/bin/env python3

# Use the proper idiom in the main module ...
# NOTE: See https://docs.python.org/3.13/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; run \"pip install --user PyGuymer3\"") 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", mode = "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")
                exif = iObj.getexif()

            # 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 exif.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.optimise_image(
                    png1,
                      strip = True,
                    timeout = 3600.0,   # NOTE: Would normally be "60.0".
                )

            # 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.optimise_image(
                    png2,
                      strip = True,
                    timeout = 3600.0,   # NOTE: Would normally be "60.0".
                )

        # Save JSON ...
        with open("miniscale.json", mode = "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
115
116
117
118
119
120
121
122
123

#!/usr/bin/env python3

# Use the proper idiom in the main module ...
# NOTE: See https://docs.python.org/3.13/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; run \"pip install --user PyGuymer3\"") 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", mode = "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")
                exif = iObj.getexif()

            # 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 exif.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.optimise_image(
                    png1,
                      strip = True,
                    timeout = 3600.0,   # NOTE: Would normally be "60.0".
                )

            # 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.optimise_image(
                    png2,
                      strip = True,
                    timeout = 3600.0,   # NOTE: Would normally be "60.0".
                )

        # Save JSON ...
        with open("overview.json", mode = "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
115
116
117
118
119
120
121
122
123

#!/usr/bin/env python3

# Use the proper idiom in the main module ...
# NOTE: See https://docs.python.org/3.13/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; run \"pip install --user PyGuymer3\"") 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", mode = "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")
                exif = iObj.getexif()

            # 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 exif.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.optimise_image(
                    png1,
                      strip = True,
                    timeout = 3600.0,   # NOTE: Would normally be "60.0".
                )

            # 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.optimise_image(
                    png2,
                      strip = True,
                    timeout = 3600.0,   # NOTE: Would normally be "60.0".
                )

        # Save JSON ...
        with open("raster.json", mode = "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

.editorconfig
.gitignore
.mypy.ini
.pylint.ini
.shellcheckrc
git-files.txt
miniscale.json
README.md

              
You may also download “git-files.txt” directly or view “git-files.txt” on GitHub Gist (you may need to manually checkout the “main” branch).
1
2
3
4
5
6
7
8

.editorconfig
.gitignore
.mypy.ini
.pylint.ini
.shellcheckrc
git-files.txt
overview.json
README.md

              
You may also download “git-files.txt” directly or view “git-files.txt” on GitHub Gist (you may need to manually checkout the “main” branch).
1
2
3
4
5
6
7
8

.editorconfig
.gitignore
.mypy.ini
.pylint.ini
.shellcheckrc
git-files.txt
raster.json
README.md

              
You may also download “git-files.txt” directly or view “git-files.txt” 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
134
135
136
137

#!/usr/bin/env python3

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

    # Import special modules ...
    try:
        import cartopy
        cartopy.config.update(
            {
                "cache_dir" : pathlib.PosixPath("~/.local/share/cartopy").expanduser(),
            }
        )
    except:
        raise Exception("\"cartopy\" is not installed; run \"pip install --user Cartopy\"") from None
    try:
        import matplotlib
        matplotlib.rcParams.update(
            {
                       "axes.xmargin" : 0.01,
                       "axes.ymargin" : 0.01,
                            "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,
                "image.interpolation" : "none",                                 # NOTE: See https://matplotlib.org/stable/gallery/images_contours_and_fields/interpolation_methods.html
                     "image.resample" : False,
            }
        )
        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; run \"pip install --user PyGuymer3\"") from None

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

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

    # Create short-hand for the colour map ...
    cmap = matplotlib.colormaps["turbo"]

    # Load tile metadata ...
    with open("OrdnanceSurveyBackgroundImages/miniscale.json", mode = "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,
        debug = False,
         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"],
           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.optimise_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
134
135
136
137

#!/usr/bin/env python3

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

    # Import special modules ...
    try:
        import cartopy
        cartopy.config.update(
            {
                "cache_dir" : pathlib.PosixPath("~/.local/share/cartopy").expanduser(),
            }
        )
    except:
        raise Exception("\"cartopy\" is not installed; run \"pip install --user Cartopy\"") from None
    try:
        import matplotlib
        matplotlib.rcParams.update(
            {
                       "axes.xmargin" : 0.01,
                       "axes.ymargin" : 0.01,
                            "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,
                "image.interpolation" : "none",                                 # NOTE: See https://matplotlib.org/stable/gallery/images_contours_and_fields/interpolation_methods.html
                     "image.resample" : False,
            }
        )
        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; run \"pip install --user PyGuymer3\"") from None

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

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

    # Create short-hand for the colour map ...
    cmap = matplotlib.colormaps["turbo"]

    # Load tile metadata ...
    with open("OrdnanceSurveyBackgroundImages/overview.json", mode = "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,
        debug = False,
         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"],
           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.optimise_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
134
135
136
137

#!/usr/bin/env python3

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

    # Import special modules ...
    try:
        import cartopy
        cartopy.config.update(
            {
                "cache_dir" : pathlib.PosixPath("~/.local/share/cartopy").expanduser(),
            }
        )
    except:
        raise Exception("\"cartopy\" is not installed; run \"pip install --user Cartopy\"") from None
    try:
        import matplotlib
        matplotlib.rcParams.update(
            {
                       "axes.xmargin" : 0.01,
                       "axes.ymargin" : 0.01,
                            "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,
                "image.interpolation" : "none",                                 # NOTE: See https://matplotlib.org/stable/gallery/images_contours_and_fields/interpolation_methods.html
                     "image.resample" : False,
            }
        )
        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; run \"pip install --user PyGuymer3\"") from None

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

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

    # Create short-hand for the colour map ...
    cmap = matplotlib.colormaps["turbo"]

    # Load tile metadata ...
    with open("OrdnanceSurveyBackgroundImages/raster.json", mode = "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,
        debug = False,
         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"],
           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.optimise_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. 256 px × 256 px (0.1 Mpx; 66.2 KiB)
  2. 512 px × 512 px (0.3 Mpx; 197.8 KiB)
  3. 1,024 px × 1,024 px (1.0 Mpx; 529.7 KiB)
  4. 2,048 px × 2,048 px (4.2 Mpx; 1.4 MiB)
  5. 2,160 px × 2,160 px (4.7 Mpx; 1.3 MiB)
Download:
  1. 256 px × 256 px (0.1 Mpx; 51.7 KiB)
  2. 512 px × 512 px (0.3 Mpx; 122.2 KiB)
  3. 1,024 px × 1,024 px (1.0 Mpx; 345.3 KiB)
  4. 2,048 px × 2,048 px (4.2 Mpx; 1.1 MiB)
  5. 2,160 px × 2,160 px (4.7 Mpx; 961.7 KiB)
Download:
  1. 256 px × 256 px (0.1 Mpx; 85.4 KiB)
  2. 512 px × 512 px (0.3 Mpx; 293.6 KiB)
  3. 1,024 px × 1,024 px (1.0 Mpx; 920.6 KiB)
  4. 2,048 px × 2,048 px (4.2 Mpx; 2.6 MiB)
  5. 2,160 px × 2,160 px (4.7 Mpx; 2.5 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.