sosoc / croc

Ocean colour with R
3 stars 1 forks source link

colour images #13

Open mdsumner opened 3 years ago

mdsumner commented 3 years ago

library(readr)
cl <- readr::cols(
  .default = col_double(),
  Date.time.UTC = col_datetime(format = ""),
  activity = col_character(),
  feature = col_logical(),
  speed.status = col_character(),
  type = col_character(),
  notes = col_character(),
  lon.ddm = col_character(),
  lat.ddm = col_character(),
  delta.time = col_datetime(format = ""),
  delta.time.AEDT = col_datetime(format = "")
)

r2rgb <- function(x) {
  cols <- x@legend@colortable
  rx <- raster(x)
  setValues(brick(rx, rx, rx), t(col2rgb(cols[values(x) + 1])))
}

date <- as.Date("2021-01-14")
YR <- format(date, "%Y")
JD <- format(date, "%j")
VAR <- ""
rr <- "9km"  ## 4km or 9km
resol <- switch(rr, 
                "4km" = 360/8640, 
                "9km" = 360/4320)
library(raster)
r <- raster(extent(-180, 180, -90, 90), res = resol, crs = "+proj=longlat +datum=WGS84")
url <- glue::glue("https://oceancolor.gsfc.nasa.gov/showimages/VIIRS/IMAGES/CHL/L3/{YR}/{JD}/V{YR}{JD}.L3m_DAY_SNPP_CHL_chlor_a_{rr}.nc.png")
       #https://oceancolor.gsfc.nasa.gov/showimages/MODISA/IMAGES/CHL/L3/2021/016/A2021016.L3m_DAY_CHL_chlor_a_4km.nc.png

tf <- file.path(tempdir(), basename(url))
if (!file.exists(tf)) curl::curl_download(url, tf)
g <- brick(tf)
extent(g) <- extent(r)
ex <- extent(range(v$lon), range(v$lat))

plotRGB(r2rgb(crop(g, ex)))

## calculate period of mean chla
library(raadtools)
oc <- ocfiles("daily", product = "MODISA", var = "CHL", type = "L3m")
date0 <- as.POSIXct("2020-12-20")
ex <- extent(55, 80, -70, -50)
files <- subset(oc, date >= date0)
br <- brick(lapply(files$fullname, function(fil) crop(raster(fil, varname = "chlor_a"), ex)))

mn <- mean(br, na.rm = TRUE)
library(palr)
pal <- chl_pal(palette = TRUE)
plot(mn, col = pal$cols, breaks = pal$breaks, legend = FALSE)
v