I have working code for normalizing an image. Is there a more efficient way to achieve the same result and cut down on the steps involved?
Asking because after finalizing this workflow on a per-Image basis, will want to adapt to a per-ImageCollection workflow (not sure how to do that yet) to extract time series.
Using rgee with Google Earth Engine.
Thank you!
# Load libraries
library(rgee)
# Initialize gee
ee_Initialize()
# Define ImageCollection
viirs <- ee$ImageCollection("NOAA/VIIRS/DNB/MONTHLY_V1/VCMSLCFG")$
filterDate("2020-01-01", "2020-01-31")$
select('avg_rad')$
first()
# Define AOI
tls <- ee$Feature(ee$FeatureCollection("FAO/GAUL/2015/level0")$
filter(ee$Filter$eq('ADM0_NAME', 'Republic of Korea'))$
first())$
geometry()
# Clip
ntl_tls <- viirs$clip(tls)
# Calculate mean and SD
mu <- ntl_tls$reduceRegion(reducer=ee$Reducer$mean())
std <- ntl_tls$reduceRegion(reducer=ee$Reducer$stdDev())
# Cast these to native ee Numbers using the ee.Number constructor
mu <- ee$Number(mu$get('avg_rad'))
std <- ee$Number(std$get('avg_rad'))
# By pixel: Subtract mean and divide by SD to normalize
ntl_tls_clean <- ntl_tls$subtract(mu)$divide(std)
# Extract computation
NTL <- ee_extract(
x = ntl_tls_clean,
y = tls,
scale = 20,
fun = ee$Reducer$sum(),
sf = FALSE
)
# Show result (one data point)
print(NTL)
For sanity check, can plot map for the two images (original vs normalized):
# Plot raw map for sanity check
Map$centerObject(ntl_tls, zoom=7)
map_raw <- Map$addLayer(
eeObject = ntl_tls,
visParams = list(
#min=0,
#max=0.0002,
palette=c('000000','700000','808080','FFFF00','ffffff','ffffff','ffffff')
))
map_raw
# Plot cleaned map for sanity check
Map$centerObject(ntl_tls_clean, zoom=7)
map_clean <- Map$addLayer(
eeObject = ntl_tls_clean,
visParams = list(
#min=0,
#max=0.0002,
palette=c('000000','700000','808080','FFFF00','ffffff','ffffff','ffffff')
))
map_clean