def toBinary(samplingIndices):
    """
    Converts the structure returned by `createSamplingIndices` into a binary
    form, appropriate for storing in a cache file.
    """

    # Local variables for functions improve peformance, according to timing tests.
    # See https://wiki.python.org/moin/PythonSpeed/PerformanceTips
    toBytes = int.to_bytes

    ba = bytearray()
    for pixel in samplingIndices:
        for sample in pixel:
            ba += toBytes(sample[0], 1, "big")
            ba += toBytes(sample[1], 2, "big")
            ba += toBytes(sample[2], 2, "big")
    return ba