rrgbmaskimager

How to apply a binary mask to a RGB image in R with imager


I have loaded in a RGB image with the imager::load.image() function. I have also created a binary mask with the imager::threshold() function.

RGB_image Mask

I am able to apply this mask to binary images by doing this:

red_channel <- R(RGB_image)
green_channel <- G(RGB_image)
blue_channel <- B(RGB_image)

red_channel <- red_channel * Mask
green_channel <- green_channel * Mask
blue_channel <- blue_channel * Mask

However RGB_image * Mask does not work because the RGB image has more dimensions than the binary mask.

So I need either a function in R to apply a binary mask to an RGB image. Or alternatively a way to combine a red, green, and blue image into a RGB image.

I have a very strong preference to do this in R and a light preference to keep using the imager package if possible.


Solution

  • I figured out my own question after some experimenting. This function does the trick, it does depend on the imager package.

    RGBimage should be an RGB image loaded in by imager:load.image() Bthreshold should be a binary threshold consisting of TRUE and FALSE values.

    apply_rgb_mask <-function(RGBimage, Bthreshold){
    red <- R(RGBimage) * Bthreshold
    green <- G(RGBimage) * Bthreshold
    blue <- B(RGBimage) * Bthreshold
    return(imappend(list(red, green, blue), "c"))
    }