【问题标题】:How to save images returned with a loop in R to hard drive?如何将 R 中循环返回的图像保存到硬盘驱动器?
【发布时间】:2021-06-27 11:24:52
【问题描述】:

我有一个带有纬度和经度坐标的 csv 文件。一个样本:

Lat   Lon
94.2  13.4
32.2  12.4
89.3  24.4

下面的代码循环遍历这些纬度/经度坐标,在 Google 街景中找到该位置的相关图像,然后我可以在代码单元下方的 R Markdown 中看到。

但是,使用上面的示例数据,会返回 3 张图像。我想将它们保存到我工作目录之外的特定“图像”文件夹中的硬盘驱动器中。有没有办法做到这一点?

# install.packages('googleway')

myfunction <- function(Lat, Lon){
  google_streetview(
  location = c(Lat, Lng), # lat/lon coordinates
  size = c(600, 400), # w x h
)
}

purrr::map2(data$Lat, data$Lon, myfunction)

【问题讨论】:

  • @R_Dax ish - 这只是我的代码中的循环使用完整数据返回许多图像(10,000+)。我希望将它们全部下载到我的外部硬盘驱动器(因为我的计算机太低而无法保存这么多图像),但是由于图像太多,我无法使用filename 命名所有图像。有什么想法吗?
  • @RonakShah 我没有,因为我不知道用什么来保存它们。理想情况下,我想将图像保存为 jpeg,而不必先在 R 中查看它们。

标签: r loops


【解决方案1】:
  1. 构建一个包含纬度/经度对的列表
  2. 在创建单个图表的函数中包含“保存到磁盘”步骤
  3. 使用lapply 将函数依次应用于列表的每个元素

例如,以下(未经测试的)代码应将您的图像保存在名为image00001.jpgimg00002.jpg 等的一系列文件中。

library(tidyverse)

positions <- list(c("lat"=94.2, "lon"=13.4),c("lat"=32.2, "lon"=12.4),c("lat"=89.3, "lon"=24.2))
imgCount <- 0
lapply(
  positions,
  function(x) {
    google_streetview(
      location = c(x$lat, x$lon), # lat/lon coordinates
      size = c(600, 400), # w x h
    )
    imgCount <<- imgCount + 1
    ggsave(paste0("image", sprintf("%05d", imgCount), ".jpg"))
  }
)

注意使用&lt;&lt;- 以确保计数器正确递增。

【讨论】:

    【解决方案2】:

    你能看看以下是否有效吗?我无法运行google_streetview(),因为我没有 API 密钥。但如果输出是“情节”,它应该可以工作。

    在中间步骤中,我们生成了一个id 变量,以便能够将每个图与每个图像相匹配,以及每个图的文件名。您可以调整文件名以确保它保存在所需的位置。

    library(dplyr)
    library(purrr)
    
    df <- tribble(
      ~Lat,    ~Lon,
      94.2, 13.4, 
      32.2, 12.4, 
      89.3, 24.4
    )
    df <- df %>% 
      mutate(id = row_number(), 
             filename = paste0("./stview_", id, ".jpeg" ))
    
    df
    
    myfunction <- function(Lat, Lon, filename, ...){
      cat("Lat: ", Lat, "\n")
      cat("Lon", Lon, "\n")
      cat("filename", filename, "\n")
      
      png(filename) # opens device.
    
      google_streetview(
        location = c(Lat, Lon), # lat/lon coordinates
        size = c(600, 400), # w x h
        output = "plot"
      )
    
      dev.off() # closes device
      print(paste("Saved:", filename))
    }
    
    
    df %>%  pwalk(myfunction)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      相关资源
      最近更新 更多