rimage-processingrgbcolor-space

Colorspace transformation for an image in R


I want to transform the colorspace of a .TIFF file from RGB to lαβ in R. There is base package grDevices which allows you to change the colorspace using the function convertColor. This doesn't have any option for lαβ.

If there are any existing functions or libraries it'll be very helpful.

I tried the following approach, but it has different lαβ tables for each of the three colors, i.e., Red, Green, and Blue:

library(schemr)
HCC1_lab_r <- rgb_to_lab(HCC1[,,1], transformation = "sRGB")

EDIT: https://entuedu-my.sharepoint.com/:i:/g/personal/bchua024_e_ntu_edu_sg/Ee74d3QJH0FGk5OivZDobx0B9qrwOaNqVx8xnCJW20uxPQ?e=SCaouY

here's the link to the image I'm trying to convert.


Solution

  • You can use the colorspace package to do such a conversion, as follows:

    library(colorspace)
    rgbcol <- RGB(1, 0, 0)
    as(rgbcol, "LAB")
    

    EDIT

    For the updated question:

    # get a tiff image as a RGBA array
    library(tiff)
    Rlogo <- system.file("img", "Rlogo.tiff", package = "tiff")
    img <- readTIFF(Rlogo)
    # remove the fourth channel (A - the transparency)
    img <- img[, , -4]
    
    # convert the `img` array to LAB
    library(colorspace)
    img <- 
      apply(img, 1:2, function(rgb) as(RGB(rgb[1], rgb[2], rgb[3]), "LAB")@coords)
    # restore the order of the dimensions
    img <- aperm(img, c(2, 3, 1))