# Coloring a binary mask image

My answer to this question involved changing the white in a binary mask to a different color.

I came up with a few ways to do this:

colorizeMask1[im_, color_] := ColorReplace[im, 1 -> color]

colorizeMask2[im_, color_] := Colorize[im, {ColorRules -> {0 -> Black, 1 -> color}}]

colorizeMask3[im_, color_] := ReplacePixelValue[im, PixelValuePositions[im, 1] -> color]

colorizeMask4[im_, color_] := ColorCombine[(List @@ color) * im]

colorizeMask5[im_, color_] := ImageMultiply[im, ConstantImage[color, ImageDimensions[im]]]


I'm not quite satisfied with any of these: they are either slow or seem too round-about.

im = Binarize[RegionImage[Annulus[], RasterSize -> 1024]];


First[AbsoluteTiming[#[im, Green];]] & /@

{0.252601, 2.45989, 0.084044, 0.011478, 0.035167}


Is there a faster, built in way to do this?

• 0.01s seems pretty quick to me, what is your time goal? Colorize would be my go-to but I accept that 2.5s is too slow! Commented Oct 12, 2018 at 18:11
• @CarlLange perhaps my question is not well enough defined. My fast solutions seemed roundabout and less obvious to attempt. The obvious looking solutions are slow. I thought perhaps I was overlooking something. Commented Oct 12, 2018 at 18:13
• Can't test right now, but I remember doing this by taking the Outer[] product of the binary image's ImageData[] with the RGB triplet of the new color (treated as a vector). Commented Oct 12, 2018 at 18:29

ImageMultiply[im, Green] // AbsoluteTiming


versus 0.031786 for colorizeMask4 (fastest of the five in OP).

• Thank you. I had tried im * Green thinking * would be equivalent to ImageMultiply in this case! Commented Oct 12, 2018 at 19:04
• @ChipHurst, my pleasure. Thank you for the accept.
– kglr
Commented Oct 12, 2018 at 19:05
• Also note that this is a 'Basic Example' in the ImageMultiply docs! Commented Oct 12, 2018 at 19:07
• @Chip, although I almost always use this form, somehow today it was the last one I tried:)
– kglr
Commented Oct 12, 2018 at 19:09
• It also works with ImageSubtract: ImageSubtract[im, RGBColor[1, 0, 1]] Commented Oct 12, 2018 at 19:15

Alternatively, ColorCombine the mask with an all-black image:

im = Binarize[RegionImage[Annulus[], RasterSize -> 1024]];
black = ImageMultiply[im, 0];
ColorCombine[{black, im, black}] // AbsoluteTiming


this takes 0.001806 vs 0.019607 for colorizeMask4