问题描述
我正在使用一个函数来下载谷歌地图图像,给出该地区的一对纬度和经度。我可以设法将下载图像的格式更改为 jpeg 或 png 或 tiff,但我想将图像保存为 Geotiff 以保留空间信息。有没有办法做到这一点?就像输入现有图像,然后输入我想要转换的格式一样。这是代码
def __init__(self,lat,lng,zoom=12,layer='s'):
self._lat = lat
self._lng = lng
self._zoom = zoom
self._layer = layer
def getXY(self):
tile_size = 256
numTiles = 2 << self._zoom
# Find the x_point given the longitude
point_x = (tile_size / 2 + self._lng * tile_size / 360.0) * numTiles // tile_size
# Convert the latitude to radians and take the sine
sin_y = math.sin(self._lat * (math.pi / 180.0))
# Calulate the y coorindate
point_y = ((tile_size / 2) + 0.5 * math.log((1 + sin_y) / (1 - sin_y)) * -(
tile_size / (2 * math.pi))) * numTiles // tile_size
return int(point_x),int(point_y)
def generateTiles(self,**kwargs):
start_x = kwargs.get('start_x',None)
start_y = kwargs.get('start_y',None)
tile_width = kwargs.get('tile_width',5)
tile_height = kwargs.get('tile_height',5)
# Check that we have x and y tile coordinates
if start_x == None or start_y == None:
start_x,start_y = self.getXY()
# Determine the size of the image
width,height = 256 * tile_width,256 * tile_height
# Create a new image of the size require
map_img = Image.new('RGB',(width,height))
for x in range(0,tile_width):
for y in range(0,tile_height):
url = f'https://mt0.google.com/vt?lyrs={self._layer}&x=' + str(start_x + x) + '&y=' + str(start_y + y) + '&z=' + str(self._zoom)
current_tile = str(x) + '-' + str(y)
urllib.request.urlretrieve(url,current_tile)
im = Image.open(current_tile)
map_img.paste(im,(x * 256,y * 256))
os.remove(current_tile)
current_tile = str(x) + '-' + str(y)
urllib.request.urlretrieve(url,y * 256))
os.remove(current_tile)
return map_img
def main():
gmd = ImagesDownloader(lat,lon,15,layer ='s')
print("The tile coorindates are {}".format(gmd.getXY()))
try:
# Get the high resolution image
img = gmd.generateTiles()
except IOError:
print("Could not generate the image - try adjusting the zoom level and checking your coordinates")
else:
# Save the image to disk
img.save("high_resolution_image.tif")
print("The map has successfully been created")
if __name__ == '__main__': main()
解决方法
我建议使用 GDAL 来创建 GeoTiff。如果您正在工作,则可以使用 Python 绑定。https://gdal.org/api/python.html您可能需要检查地图服务的使用条款,通常不允许导出和保存图像。