如何使用 python 从街景静态 API 渲染请求的图像?

How can I render a requested image from Street View Static API using python?

我使用了请求:

导入请求

url = 'https://maps.googleapis.com/maps/api/streetview?size=400x400&location=40.720032,-73.988354&heading=0&key=[YOUR KEY HERE]'

r = requests.get(url)

我在 r.contents 中得到了这个(我如何将这些字节转换为图像?我尝试了 PIL 和 matplotlib 但无法使其工作):

b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0c\x14\r\x0c\x0b\x0b\x0c\x19\x12\x13\x0f\x14\x1d\x1a\x1f\x1e\x1d\x1a\x1c\x1c $.\' ",#\x1c\x1c(7),01444\x1f\'9=82<.342\xff\xdb\x00C\x01\t\t\t\x0c\x0b\x0c\x18\r\r\x182!\x1c!22222222222222222222222222222222222222222222222222\xff\xc0\x00\x11\x08\x01\x90\x01\x90\x03\x01"\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x1f\x00\x00\x01\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\xff\xc4\x00\xb5\x10\x00\x02\x01\x03\x03\x02\x04\x03\x05\x05\x04\x04\x00\x00\x01}\x01\x02\x03\x00\x04\x11\x05\x12!1A\x06\x13Qa\x07"q\x142\x81\x91\xa1\x08#B\xb1\xc1\x15R\xd1\xf0br\x82\t\n\x16\x17\x18\x19\x1a%&\'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x83\.................\xd9'

您可以使用 numpy:

加载矩阵
pixels = np.frombuffer(r.content, dtype=np.uint8)

然后创建一个 PIL 图像:

image = Image.fromarray(pixels 'RGB')

我认为解决您的问题的方法是更改​​这部分代码:

r = requests.get(url) # will only wait for one response and exit

你应该替换成

r = requests.get(url, stream=True) # will stream data until finished

我认为问题在于,截至目前,您的代码在收到整个图像数据之前就过早退出了。这也是为什么您的对象对于 400x400 的图像来说显得太小的原因。

干杯,

丹尼斯