RGB to HLS raster conversion with R

Hello digital World!

As my first blog post, here is a note about how to convert a RGB raster to HLS color space with R. I remember having searched the web quite a long time before finding an efficient way.

We use the raster and colorspace packages:

library(raster)
library(rgdal)
library(colorspace)

First, read the RGB raster stack:

bands <- stack("image.tif")

and create output:

hls <- setValues(stack(bands[[1:3]]), NA)

Convert RGB to HLS:

values(hls) <- colorspace::coords(
  as(
    colorspace::RGB(
      getValues(bands[[1:3]])
    ), "HLS"
  )
)

finally, rename output bands:

names(hls) <- c("H", "L", "S")