0

I used requests:

import requests

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)

and I get this in r.contents (how do I turn these bytes to an image? I tried PIL and matplotlib but could not make it work):

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\xf0$3br\x82\t\n\x16\x17\x18\x19\x1a%&\'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x83\.................\xd9'

2 Answers2

0

You can load a matrix with numpy:

pixels = np.frombuffer(r.content, dtype=np.uint8)

Then create a PIL Image with:

image = Image.fromarray(pixels 'RGB')
  • Thanks a lot for your help! I tried this and also Image.frombuffer('RGB',(400,400),r.content) but still can't render the image. These are my headers: {'Content-Type': 'image/jpeg', ... 'Content-Length': '27707'...} I Think the problem could be related to the size of the request, like I should be getting 400x400 = 16k * 3 but I get a smaller number, so I get the ValueError: not enough image data error. As for using numpy, I get a vector with a single dimension and the Image process crashes when it can't find pixels.shape[1] – Sergio Ferro Sep 28 '19 at 23:03
0

I think what solves your issue is changing this part of your code:

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

you should replace with

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

I think the issue is that as of right now your code exits prematurely before the whole imagedata was received. That's also why your object appears to be too small for a 400x400 image.

Cheers,

Dennis

Dennis
  • 145
  • 1
  • 8