Last active
December 23, 2024 09:17
-
-
Save kadyb/2bb2ee62b901739d68fbd50e765a0a64 to your computer and use it in GitHub Desktop.
Sentinel-2 L2A True Color Optimized in R and terra
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Original source: https://custom-scripts.sentinel-hub.com/sentinel-2/l2a_optimized/ | |
enhanceRGB = function(x, maxR = 3, midR = 0.13, sat = 1.2, gamma = 1.8, | |
cores = 1) { | |
## functions ----------------------------------------------------------------- | |
sAdj = function(a) { | |
adjGamma(adj(a, midR, 1, maxR)) | |
} | |
gOff = 0.01 | |
gOffPow = gOff**gamma | |
gOffRange = (1 + gOff)**gamma - gOffPow | |
adjGamma = function(b) { | |
((b + gOff)**gamma - gOffPow) / gOffRange | |
} | |
adj = function(a, tx, ty, maxC) { | |
ar = a / maxC | |
ar * (ar * (tx / maxC + ty - 1) - ty) / (ar * (2 * tx / maxC - 1) - tx / maxC) | |
} | |
satEnh = function(r, ...) { | |
avgS = mean(terra::global(r, fun = "mean", na.rm = TRUE)[["mean"]]) | |
f = function(band, ...) {avgS + band * sat} | |
r[[1]] = terra::lapp(r[[1]], fun = f, cores = cores) | |
r[[2]] = terra::lapp(r[[2]], fun = f, cores = cores) | |
r[[3]] = terra::lapp(r[[3]], fun = f, cores = cores) | |
r = terra::clamp(r, lower = 0, upper = 1, values = TRUE) | |
return(r) | |
} | |
sRGB = function(c) { | |
thresh = 0.0031308 | |
c = terra::ifel( | |
c <= thresh, | |
12.92 * c, | |
(1.055 * c**0.41666666666) - 0.055 | |
) | |
return(c) | |
} | |
## processing ---------------------------------------------------------------- | |
x = terra::clamp(x, lower = 0, upper = 1, values = TRUE) | |
x = terra::app(x, fun = sAdj, cores = cores) | |
x = sRGB(satEnh(x, sat)) | |
return(x) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment