import PIL.Image as Image import PIL.ImageDraw as ImageDraw import PIL.ImagePath as ImagePath import xml.etree.ElementTree as ET import pyproj proj_mapdata = pyproj.Proj(proj = 'longlat', ellps = 'WGS84') proj_image = pyproj.Proj(proj = 'merc', ellps = 'WGS84') imagecoords = (24.65, 60.28, 24.67, 60.27) image = Image.open('wms_2465_2467_6027_6028.png') data = ET.parse('teach_2465_2467_6027_6028.osm').getroot() image_topleft = pyproj.transform(proj_mapdata, proj_image, imagecoords[0], imagecoords[1]) image_bottomright = pyproj.transform(proj_mapdata, proj_image, imagecoords[2], imagecoords[3]) def latlon_to_image(lat, lon): x, y = pyproj.transform(proj_mapdata, proj_image, lon, lat) x = (x - image_topleft[0]) * image.size[0] / (image_bottomright[0] - image_topleft[0]) y = (y - image_topleft[1]) * image.size[1] / (image_bottomright[1] - image_topleft[1]) return int(x), int(y) # Map node id's to coordinates in picture nodes = {} for node in data.getiterator('node'): id = int(node.attrib.get('id')) lat = float(node.attrib.get('lat')) lon = float(node.attrib.get('lon')) nodes[id] = latlon_to_image(lat, lon) ways = {} for way in data.getiterator('way'): id = int(way.attrib.get('id')) points = [] for node in way.getiterator('nd'): node_id = int(node.attrib.get('ref')) points.append(nodes[node_id]) ways[id] = points def get_tags(obj): tags = {} for tag in obj.getiterator('tag'): tags[tag.get('k')] = tag.get('v') return tags include = [] exclude = [] exclude_roads = [] for way in data.getiterator('way'): id = int(way.get('id')) tags = get_tags(way) if tags.get('natural') == 'wood' or tags.get('landuse') == 'forest': include.append(ways[id]) elif (tags.get('natural') or tags.get('landuse') or tags.get('building') or tags.get('leisure')): exclude.append(ways[id]) elif tags.get('highway'): exclude_roads.append(ways[id]) for relation in data.getiterator('relation'): tags = get_tags(relation) if tags.get('natural') == 'wood' or tags.get('landuse') == 'forest': role_include = 'outer' role_exclude = 'inner' elif (tags.get('natural') or tags.get('landuse') or tags.get('building') or tags.get('leisure')): role_include = 'inner' role_exclude = 'outer' else: continue for member in relation.getiterator('member'): id = int(member.get('ref')) if not ways.has_key(id): continue if member.get('role') == role_include: include.append(ways[id]) elif member.get('role') == role_exclude: exclude.append(ways[id]) image = Image.new('RGB', image.size) draw = ImageDraw.Draw(image) for path in include: draw.polygon(path, fill = (0,255,0)) for path in exclude: draw.polygon(path, fill = (255,0,0)) for path in exclude_roads: draw.line(path, fill = (255,0,0), width = 5) image.save('mask.png')