Roga Lu
Roga Lu

Reputation: 162

How to save as image response of google streetview API in R?

I need to save the as image (.jpg, .png) the result from google_streetview API

I'm working in a small project to test an image recognition algorith. I'm downloading some images from google street, I need to save this images as .jpg or .png format.

 library(googleway)

 p <- google_streetview(location = c(centerlat,centerlng),              
              size = c(500,500),                
              panorama_id = NULL,               
              output = "plot",              
              heading = 0,              
              fov = 15,             
              pitch = 0,                
              response_check = FALSE,               
              key = key)

I have tried to use download.file and the library imager:

First:

 download.file(p, destfile="test.jpg")

Error in if (stringr::str_count(imagePath, "http") > 0) { : argument is of length zero

Second:

 library(imager)
 imager::save.image(p,"test.jpeg")

Error in imager::save.image(p, "test.jpeg") : First argument should be an image

How can I save this images automatically?

Upvotes: 0

Views: 879

Answers (1)

Spacedman
Spacedman

Reputation: 94212

This is a bit of a guess since I don't have an API key.

This is the last bit of google_streetview function:

map_url <- constructURL(map_url, c(location = location, pano = panorama_id, 
    size = size, heading = heading, fov = fov, pitch = pitch, 
    key = key))
if (output == "plot") {
    z <- tempfile()
    utils::download.file(map_url, z, mode = "wb")
    pic <- jpeg::readJPEG(z)
    file.remove(z)
    graphics::plot(0:1, 0:1, type = "n", ann = FALSE, axes = FALSE)
    return(graphics::rasterImage(pic, 0, 0, 1, 1))
}
else {
    return(map_url)
}

Note that if output="plot" then the map_url is downloaded to tempfile, which is read in to a jpeg, which is then plotted, and the temp file removed. How can we get to that jpeg?

If output="html" then the map_url is returned. This must be the URL of the image. So call with output="html" and store the return value, and then download:

url = google_streetview(..., output="html")
t = tempfile()
download.file(url, t, model="wb")
message(t, " should be a JPEG...")

You've tried to do it with output="plot" in which case it returns return(graphics::rasterImage(pic, 0, 0, 1, 1)) which is always a NULL value.

Upvotes: 2

Related Questions