如何使用Python从地图图像中提取接壤国家信息
地图邻国提取需求与预处理实现
核心需求
我有一张带彩色国家区域和黑色边界的地图,需要实现一套方法,提取出每个红色标记国家的所有蓝色标记接壤邻国,最终输出符合以下格式的JSON:
{ "country1":{ "neighbours":["country2","country3","country4","country5","country6","country7","country8"] }, "country2":{ "neighbours":["country1","country8","country9","country10"] }, ... }
已完成的预处理工作
目前已按照建议,使用PIL和potrace将位图地图转换为SVG矢量格式,转换效果对应指定截图,实现代码如下:
import os from PIL import Image threshold = 620 file_in = "/Users/nils/Documents/map.png" img = Image.open(file_in) pixels = list(img.getdata()) newPixels = [] for pixel in pixels: if pixel[0]+pixel[1]+pixel[2] <= threshold: newPixel = (0, 0, 0) else: newPixel = (255, 255, 255) newPixels.append(newPixel) newImg = Image.new(img.mode, img.size) newImg.putdata(newPixels) file_out = "test.bmp" print(len(newImg.split())) # 测试用 if len(newImg.split()) == 4: print("转换中") r, g, b, a = newImg.split() newImg = Image.merge("RGB", (r, g, b)) newImg.save(file_out) else: newImg.save(file_out) os.system("potrace test.bmp --svg -o my.svg")
内容的提问来源于stack exchange,提问作者nonline
相关产品推荐
相关产品推荐

