You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Bing Maps API绘图:缩放时保持背景色恒定

解决Bing Maps高缩放级别下Matplotlib背景色反转问题

当缩放级别设为16或更高时,Bing Maps返回的静态地图图像会带上Alpha透明通道(RGBA格式),而Matplotlib的imshow默认会将图像的透明区域与坐标轴背景色混合,导致原本的白色背景看起来像是反转成深色。部分高缩放级别的图像色彩空间格式转换问题,也会加剧显示异常。

直接按以下步骤修改代码即可解决:

  • 将获取到的PIL图像转换为纯RGB格式,移除Alpha通道
  • 显式设置Matplotlib坐标轴的背景色为白色,匹配Bing Maps Road地图的默认背景

修改后的完整代码:

import requests
from PIL import Image
from io import BytesIO
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon

plt.style.use('default')
API_KEY = "<你的API密钥>"
poly_str = [(26.258654470488352, 50.60623948760518), (26.260892838025025, 50.61137614053575), (26.259367564324837, 50.612537537528866), (26.257912032768143, 50.615014721155816), (26.257639268464615, 50.60718484036582)]

# 计算地图中心坐标
center_lat = sum(coord[0] for coord in poly_str) / len(poly_str)
center_lon = sum(coord[1] for coord in poly_str) / len(poly_str)
print(f"中心纬度: {center_lat}")
print(f"中心经度: {center_lon}")

# 静态地图参数
zoom_level = 16
map_size = '4000,4000'

# Bing Maps API请求URL
map_url = f"http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/{center_lat},{center_lon}/{zoom_level}?mapSize={map_size}&format=png&key={API_KEY}"

# 获取地图图像
response = requests.get(map_url)
image = Image.open(BytesIO(response.content))
# 关键修改:转换为RGB格式,移除Alpha通道
image = image.convert('RGB')

# 显示地图
fig, ax = plt.subplots(figsize=(8, 8), dpi=200)
# 关键修改:显式设置坐标轴背景色为白色
ax.set_facecolor('white')
ax.imshow(np.asarray(image), extent=[0, image.width, 0, image.height])

# 绘制多边形
polygon_coords = [(841, 678), (1086, 665), (1084, 573), (1006, 471), (866, 586)]
poly_patch = Polygon(polygon_coords, facecolor='red', alpha=0.5, edgecolor='black')
ax.add_patch(poly_patch)

plt.axis('off')
plt.show()
# plt.savefig("map_bing.jpg")

额外说明:

  • 代码补充了多边形的绘制逻辑(原代码仅定义坐标未实际绘制),不需要可直接删除
  • 转换为RGB格式后,图像不再包含透明层,避免与轴背景色混合导致的颜色异常
  • 设置轴背景色为白色,确保与Bing Maps Road地图的默认背景统一,即使存在少量残留透明区域也不会显式异常

内容的提问来源于stack exchange,提问作者Sharvari Mittal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 22:42:04