在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):r-spatial/rgee开源软件地址(OpenSource Url):https://github.com/r-spatial/rgee开源编程语言(OpenSource Language):R 97.8%开源软件介绍(OpenSource Introduction):
|
JS (Code Editor) | Python | R |
---|---|---|
var db = 'CGIAR/SRTM90_V4'
var image = ee.Image(db)
print(image.bandNames())
#> 'elevation' |
import ee
ee.Initialize()
db = 'CGIAR/SRTM90_V4'
image = ee.Image(db)
image.bandNames().getInfo()
#> [u'elevation'] |
library(rgee)
ee_Initialize()
db <- 'CGIAR/SRTM90_V4'
image <- ee$Image(db)
image$bandNames()$getInfo()
#> [1] "elevation" |
Quite similar, isn't it?. However, additional more minor changes should be considered when using Google Earth Engine with R. Please check the consideration section before you start coding!
Install from CRAN with:
install.packages("rgee")
Install the development versions from github with
library(remotes)
install_github("r-spatial/rgee")
Additionally, rgee
depends on the Python packages: numpy and ee. To install them, users can follow any of these three methods:
rgee::ee_install()
rgee::ee_install_set_pyenv(
py_path = "/home/csaybar/.virtualenvs/rgee/bin/python", # Change it for your own Python PATH
py_env = "rgee" # Change it for your own Python ENV
)
Take into account that the Python PATH you set must have installations of the Earth Engine Python API and numpy. The use of miniconda/anaconda is mandatory for Windows users, Linux and MacOS users could also use virtualenv. See reticulate documentation for more details.
Another option, only possible for MacOS and Linux, is just set the Python PATH:
rgee::ee_install_set_pyenv(
py_path = "/usr/bin/python3",
py_env = NULL
)
However, rgee::ee_install_upgrade and reticulate::py_install will not work until you set a Python ENV.
After install Python dependencies
(and Restart R!!), you might use the function below for checking the status of rgee.
ee_check() # Check non-R dependencies
library(reticulate)
library(rgee)
# 1. Initialize the Python Environment
ee_Initialize()
# 2. Install geemap in the same Python ENV that use rgee
py_install("geemap")
gm <- import("geemap")
Upgrade the earthengine-api
library(rgee)
ee_Initialize()
ee_install_upgrade()
rgee
functions have the prefix ee_. Auto-completion is your friend :).rgee
is "pipe-friendly"; we re-export %>% but do not require its use.Authenticate and Initialize the Earth Engine R API.
library(rgee)
ee_Initialize()
Adds a band containing image date as years since 1991.
createTimeBand <-function(img) {
year <- ee$Date(img$get('system:time_start'))$get('year')$subtract(1991L)
ee$Image(year)$byte()$addBands(img)
}
Map the time band creation helper over the night-time lights collection.
collection <- ee$
ImageCollection('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS')$
select('stable_lights')$
map(createTimeBand)
Compute a linear fit over the series of values at each pixel, visualizing the y-intercept in green, and positive/negative slopes as red/blue.
col_reduce <- collection$reduce(ee$Reducer$linearFit())
col_reduce <- col_reduce$addBands(
col_reduce$select('scale'))
ee_print(col_reduce)
Create an interactive visualization!
Map$setCenter(9.08203, 47.39835, 3)
Map$addLayer(
eeObject = col_reduce,
visParams = list(
bands = c("scale", "offset", "scale"),
min = 0,
max = c(0.18, 20, -0.18)
),
name = "stable lights trend"
)
Install and load tidyverse
and sf
R packages, and initialize the Earth Engine R API.
library(tidyverse)
library(rgee)
library(sf)
ee_Initialize()
Read the nc
shapefile.
nc <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
Map each image from 2001 to extract the monthly precipitation (Pr) from the Terraclimate dataset
terraclimate <- ee$ImageCollection("IDAHO_EPSCOR/TERRACLIMATE") %>%
ee$ImageCollection$filterDate("2001-01-01", "2002-01-01") %>%
ee$ImageCollection$map(function(x) x$select("pr")) %>% # Select only precipitation bands
ee$ImageCollection$toBands() %>% # from imagecollection to image
ee$Image$rename(sprintf("PP_%02d",1:12)) # rename the bands of an image
Extract monthly precipitation values from the Terraclimate ImageCollection through ee_extract
. ee_extract
works similar to raster::extract
, you just need to define: the ImageCollection object (x), the geometry (y), and a function to summarize the values (fun).
ee_nc_rain <- ee_extract(x = terraclimate, y = nc["NAME"], sf = FALSE)
Use ggplot2 to generate a beautiful static plot!
ee_nc_rain %>%
pivot_longer(-NAME, names_to = "month", values_to = "pr") %>%
mutate(month, month=gsub("PP_", "", month)) %>%
ggplot(aes(x = month, y = pr, group = NAME, color = pr)) +
geom_line(alpha = 0.4) +
xlab("Month") +
ylab("Precipitation (mm)") +
theme_minimal()
Install and load sf
, after that, initialize the Earth Engine R API.
library(magick)
library(rgee)
library(sf)
ee_Initialize()
Define the regional bounds of animation frames and a mask to clip the NDVI data by.
mask <- system.file("shp/arequipa.shp", package = "rgee") %>%
st_read(quiet = TRUE) %>%
sf_as_ee()
region <- mask$geometry()$bounds()
Retrieve the MODIS Terra Vegetation Indices 16-Day Global 1km dataset as an ee.ImageCollection
and select the NDVI band.
col <- ee$ImageCollection('MODIS/006/MOD13A2')$select('NDVI')
Group images by composite date
col <- col$map(function(img) {
doy <- ee$Date(img$get('system:time_start'))$getRelative('day', 'year')
img$set('doy', doy)
})
distinctDOY <- col$filterDate('2013-01-01', '2014-01-01')
Define a filter that identifies which images from the complete collection match the DOY from the distinct DOY collection.
filter <- ee$Filter$equals(leftField = 'doy', rightField = 'doy')
Define a join; convert the resulting FeatureCollection to an ImageCollection.
join <- ee$Join$saveAll('doy_matches')
joinCol <- ee$ImageCollection(join$apply(distinctDOY, col, filter))
Apply median reduction among matching DOY collections.
comp <- joinCol$map(function(img) {
doyCol = ee$ImageCollection$fromImages(
img$get('doy_matches')
)
doyCol$reduce(ee$Reducer$median())
})
Define RGB visualization parameters.
visParams = list(
min = 0.0,
max = 9000.0,
bands = "NDVI_median",
palette = c(
'FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718', '74A901',
'66A000', '529400', '3E8601', '207401', '056201', '004C00', '023B01',
'012E01', '011D01', '011301'
)
)
Create RGB visualization images for use as animation frames.
rgbVis <- comp$map(function(img) {
do.call(img$visualize, visParams) %>%
ee$Image$clip(mask)
})
Define GIF visualization parameters.
gifParams <- list(
region = region,
dimensions = 600,
crs = 'EPSG:3857',
framesPerSecond = 10
)
Get month names
dates_modis_mabbr <- distinctDOY %>%
ee_get_date_ic %>% # Get Image Collection dates
'[['("time_start") %>% # Select time_start column
lubridate::month() %>% # Get the month component of the datetime
'['(month.abb, .) # subset around month abbreviations
Use ee_utils_gif_* functions to render the GIF animation and add some texts.
animation <- ee_utils_gif_creator(rgbVis, gifParams, mode = "wb")
animation %>%
ee_utils_gif_annotate(
text = "NDVI: MODIS/006/MOD13A2",
size = 15, color = "white",
location = "+10+10"
) %>%
ee_utils_gif_annotate(
text = dates_modis_mabbr,
size = 30,
location = "+290+350",
color = "white",
font = "arial",
boxcolor = "#000000"
) # -> animation_wtxt
# ee_utils_gif_save(animation_wtxt, path = "raster_as_ee.gif")
rgee
is not a native Earth Engine API like the Javascript or Python client. Developing an Earth Engine API from scratch would create too much maintenance burden, especially considering that the API is in active development. So, how is it possible to run Earth Engine using R? the answer is reticulate. reticulate
is an R package designed to allow seamless interoperability between R and Python. When an Earth Engine request is created in R, reticulate
will translate this request into Python and pass it to the Earth Engine Python API
, which converts the request to a JSON
format. Finally, the request is received by the GEE Platform through a Web REST API. The response will follow the same path in reverse.
Created by: - EN and POR: Andres Luiz Lima Costa https://bit.ly/3p1DFm9 - SPA: Antony Barja Ingaruca https://ambarja.github.io/
Please note that the rgee
project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论