创建ASCII艺术世界地图

问题描述 投票:5回答:1

我想给出this GeoJSON file的ASCII艺术世界地图。

我的基本方法是将GeoJSON加载到Shapely中,使用pyproj将点转换为Mercator,然后对我的ASCII艺术网格的每个字符的几何进行命中测试。

它看起来(编辑:大多数)好,当一个本初子午线居中:

centered at lon = 0

但是以纽约市(lon_0=-74)为中心,它突然变得混乱:

enter image description here

我很确定我在这里的预测做错了。 (将ASCII地图坐标转换为lat / lon比转换整个几何体可能更有效,但我不确定如何。)

import functools
import json
import shutil
import sys

import pyproj
import shapely.geometry
import shapely.ops


# Load the map
with open('world-countries.json') as f:
  countries = []
  for feature in json.load(f)['features']:
    # buffer(0) is a trick for fixing polygons with overlapping coordinates
    country = shapely.geometry.shape(feature['geometry']).buffer(0)
    countries.append(country)

mapgeom = shapely.geometry.MultiPolygon(countries)

# Apply a projection
tform = functools.partial(
  pyproj.transform,
  pyproj.Proj(proj='longlat'),  # input: WGS84
  pyproj.Proj(proj='webmerc', lon_0=0),  # output: Web Mercator
)
mapgeom = shapely.ops.transform(tform, mapgeom)

# Convert to ASCII art
minx, miny, maxx, maxy = mapgeom.bounds
srcw = maxx - minx
srch = maxy - miny
dstw, dsth = shutil.get_terminal_size((80, 20))

for y in range(dsth):
  for x in range(dstw):
    pt = shapely.geometry.Point(
      (srcw*x/dstw) + minx,
      (srch*(dsth-y-1)/dsth) + miny  # flip vertically
    )
    if any(country.contains(pt) for country in mapgeom):
      sys.stdout.write('*')
    else:
      sys.stdout.write(' ')
  sys.stdout.write('\n')

python gis shapely map-projections ascii-art
1个回答
5
投票

我在底部编辑,发现新问题(为什么没有加拿大和Shapely和Pyproj的不可靠性)


即使它没有完全解决问题,我相信这种态度比使用pyproc和Shapely更有潜力,而且在未来,如果你会做更多的Ascii艺术,会给你更多的可能性和灵活性。首先,我将写出利弊。

PS:最初我想在你的代码中找到问题,但我在运行它时遇到了问题,因为pyproj给我一些错误。

PROS

1)我能够提取所有点(加拿大真的缺少)并旋转图像

2)处理速度非常快,因此您可以创建动画Ascii艺术。

3)一次完成打印而无需循环

CONS(已知问题,可解决)

1)这种态度绝对不能正确地转换地理坐标 - 太平面,它应该看起来更加球形

2)我没有花时间试图找到填充边框的解决方案,因此只有边框有'*'。因此,这种态度需要找到填补国家的算法。我认为它不应该是问题,因为JSON文件包含分隔的国家

3)你需要2个额外的库,除了numpy - opencv(你可以使用PIL)和Colorama,因为我的例子是动画的,我需要通过将光标移动到(0,0)而不是使用os.system来“清理”终端( 'CLS')

4)我使它只在python 3中运行。在python 2中它也可以工作但是我收到了sys.stdout.buffer的错误

将终端上的字体大小更改为最低点,以使打印的字符适合终端。字体越小,分辨率越高

动画应该看起来像地图是'旋转'enter image description here

我使用了一些代码来提取数据。步骤在评论中

import json
import sys
import numpy as np
import colorama
import sys
import time
import cv2

#understand terminal_size as how many letters in X axis and how many in Y axis. Sorry not good name
if len(sys.argv)>1:   
    terminal_size = (int(sys.argv[1]),int(sys.argv[2]))
else:
    terminal_size=(230,175)
with open('world-countries.json') as f:
    countries = []
    minimal = 0 # This can be dangerous. Expecting negative values
    maximal = 0 # Expecting bigger values than 0
    for feature in json.load(f)['features']: # getting data  - I pretend here, that geo coordinates are actually indexes of my numpy array
        indexes = np.int16(np.array(feature['geometry']['coordinates'][0])*2)
        if indexes.min()<minimal:
            minimal = indexes.min()
        if indexes.max()>maximal:
            maximal = indexes.max()
        countries.append(indexes) 

    countries = (np.array(countries)+np.abs(minimal)) # Transform geo-coordinates to image coordinates
correction = np.abs(minimal) # because geo-coordinates has negative values, I need to move it to 0 - xaxis

colorama.init()

def move_cursor(x,y):
    print ("\x1b[{};{}H".format(y+1,x+1))

move = 0 # 'rotate' the globe
for i in range(1000):
    image = np.zeros(shape=[maximal+correction+1,maximal+correction+1]) #creating clean image

    move -=1 # you need to rotate with negative values
    # because negative one are by numpy understood. Positive one will end up with error
    for i in countries: # VERY STRANGE,because parsing the json, some countries has different JSON structure
        if len(i.shape)==2:
            image[i[:,1],i[:,0]+move]=255 # indexes that once were geocoordinates now serves to position the countries in the image
        if len(i.shape)==3:
            image[i[0][:,1],i[0][:,0]+move]=255


    cut = np.where(image==255) # Bounding box
    if move == -1: # creating here bounding box - removing empty edges - from sides and top and bottom - we need space. This needs to be done only once
        max_x,min_x = cut[0].max(),cut[0].min()
        max_y,min_y = cut[1].max(),cut[1].min()


    new_image = image[min_x:max_x,min_y:max_y] # the bounding box
    new_image= new_image[::-1] # reverse, because map is upside down
    new_image = cv2.resize(new_image,terminal_size) # resize so it fits inside terminal

    ascii = np.chararray(shape = new_image.shape).astype('|S4') #create container for asci image
    ascii[:,:]='' #chararray contains some random letters - dunno why... cleaning it
    ascii[:,-1]='\n' #because I pring everything all at once, I am creating new lines at the end of the image
    new_image[:,-1]=0 # at the end of the image can be country borders which would overwrite '\n' created one step above
    ascii[np.where(new_image>0)]='*' # transforming image array to chararray. Better to say, anything that has pixel value higher than 0 will be star in chararray mask
    move_cursor(0,0) # 'cleaning' the terminal for new animation
    sys.stdout.buffer.write(ascii) # print into terminal
    time.sleep(0.025) # FPS

也许最好解释一下代码中的主要算法是什么。我喜欢尽可能使用numpy。整个事情是我假装图像中的坐标,或者它可能是什么(在你的情况下是地理坐标)是矩阵索引。我有2个Matrixes - Real Image和Charray as Mask。然后,我在真实图像中获取有趣像素的索引,并在Charray Mask中为相同的索引分配我想要的任何字母。由于这个原因,整个算法不需要单个循环。

关于未来的可能性

想象一下,您还将获得有关地形(海拔高度)的信息。让我们以某种方式创建世界地图的灰度图像,其中灰色阴影表示高度。这种灰度图像将具有形状x,y。您将使用shape = [x,y,256]准备3Dmatrix。对于3D矩阵中256个中的每个图层,您可以指定一个字母'.... ;;;; ###等等'来表示阴影。准备好后,可以拍摄灰度图像,其中任何像素实际上都有3个坐标:x,y和阴影值。因此,您将在grascale地图图像中添加3个索引数组 - > x,y,shade。您的新漫画将只是使用图层字母提取3Dmatrix,因为:

#Preparation phase
x,y = grayscale.shape
3Dmatrix = np.chararray(shape = [x,y,256])
table = '    ......;;;;;;;###### ...'
for i in range(256):
    3Dmatrix[:,:,i] = table[i]
x_indexes = np.arange(x*y)
y_indexes = np.arange(x*y)
chararray_image = np.chararray(shape=[x,y])

# Ready to print
...

shades = grayscale.reshape(x*y)
chararray_image[:,:] = 3Dmatrix[(x_indexes ,y_indexes ,shades)].reshape(x,y)

因为在这个过程中没有循环,你可以一次打印chararray,你实际上可以用巨大的FPS将电影打印到终端

例如,如果你有旋转地球的镜头,你可以做这样的事情 - (250 * 70个字母),渲染时间0.03658s

enter image description here

您可以将它变为极端并在终端中进行超分辨率,但结果FPS不是那么好:0.23157s,即大约4-5 FPS。值得注意的是,这种态度FPS很有吸引力,但终端根本无法处理打印,所以这种低FPS是由于终端的限制而不是计算,因为这种高分辨率的计算耗费0.00693s,即144 FPS。

enter image description here


大编辑 - 与上述一些陈述相矛盾

我不小心打开了原始的json文件,发现有加拿大和俄罗斯有完整的正确坐标。我错误地依赖于我们在结果中都没有加拿大的事实,所以我希望我的代码没问题。在JSON内部,数据具有不同的NOT-UNIFIED结构。俄罗斯和加拿大有'Multipolygon',所以你需要迭代它。

这是什么意思?不要依赖Shapely和pyproj。显然他们无法提取一些国家,如果他们不能可靠地做到这一点,你就不能指望他们做更复杂的事情。

修改代码后,一切都没问题

代码:这是正确加载文件的方法

...
with open('world-countries.json') as f:
    countries = []
    minimal = 0
    maximal = 0
    for feature in json.load(f)['features']: # getting data  - I pretend here, that geo coordinates are actually indexes of my numpy array

        for k in range((len(feature['geometry']['coordinates']))):
            indexes = np.int64(np.array(feature['geometry']['coordinates'][k]))
            if indexes.min()<minimal:
                minimal = indexes.min()
            if indexes.max()>maximal:
                maximal = indexes.max()
            countries.append(indexes) 

...

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.