#!/usr/bin/env python3
"""A map of the UK made up of squares
There are a bunch of these, on non-free vector stock photo sites
This one should be free and reusable by anyone.
Based on https://www.publicdomainpictures.net/en/view-image.php?image=38884
a map of the UK outline by George Hodan, released as CC0
"""
from PIL import Image
import sys
def main(x_squares):
"x_squares is the number of squares that the x axis is divided into"
im = Image.open("map-of-england.jpg")
pixels = list(im.getdata())
width, height = im.size
pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]
square_size = width // x_squares
y_squares = height // square_size
squares = []
for xs in range(x_squares):
for ys in range(y_squares):
# look at all pixels in this square: if more than half of
# them are dark, then this is a dark square
# since the image is black and white (although not thresholded)
# we can just check the red pixel
xoffset = xs * square_size
yoffset = ys * square_size
lightcount = 0
darkcount = 0
for x in range(square_size):
for y in range(square_size):
pixel = pixels[yoffset+y][xoffset+x]
if pixel[0] < 128:
darkcount += 1
else:
lightcount += 1
if darkcount > lightcount:
squares.append((xs, ys))
square_els = [''.format(x*10, y*10)
for (x, y) in squares]
fn = "uk-as-squares-{}x{}.svg".format(x_squares, y_squares)
with open(fn, mode="w", encoding="utf-8") as fp:
fp.write("""""".format(x_squares * 10, y_squares * 10, "\n".join(square_els)))
print("{} generated at {}x{}".format(fn, x_squares, y_squares))
if __name__ == "__main__":
main(int(sys.argv[1]))