# What is the algorithm behind ImageRecolor?

I'm wondering which algorithm is implemented, given that recoloring requires a lot of assumptions to really get the desired color.

For example, coloring a dark grayscale image into a light green can result in a dark green image but in Mathematica it's light.

• You can view some of the source code by doing ResourceFunction["PrintDefinitions"]@ImageRecolor - perhaps with enough spelunking you can find some of the details you're looking for. Apr 18, 2019 at 18:30

The default method is brightness preserving in the HSB colorspace.

We can compare the recolor result here:

drkGrIm = Image[{{0.2}}, ColorSpace -> "Grayscale", ImageSize -> Medium];
recolor = ImageRecolor[drkGrIm, mask -> LightGreen];
recolor // ImageData
(* ===>  {{{0.176, 0.2, 0.176}}} *)


To the result we would get by replacing the hue and saturation of the gray image with the hue and saturation from LightGreen.

darkGrayHSBColor = ColorConvert[GrayLevel[0.2], "HSB"];
lightGreenHSBColor = ColorConvert[LightGreen, "HSB"];

darkGrayHSBList = List @@ darkGrayHSBColor;
lightGreenHSBList = List @@ lightGreenHSBColor;

newColorHSB = Hue[Join[lightGreenHSBList[[;; 2]], darkGrayHSBList[[-1 ;;]]]];

ColorConvert[newColorHSB, "RGB"]
(* ===> RGBColor[0.17600000000000002, 0.2, 0.17600000000000002] *)


This matches the result from the image.

If we are not doing a complete recolor, but just a partial one, the result can be obtained with Blend.

lessIntensityMask = Image[{{0.4}}];
blendedRecolor = ImageRecolor[drkGrIm, halfIntensityMask -> LightGreen];
blendedRecolor // ImageData
(* ===> {{{0.1904, 0.2, 0.1904}}} *)


Our less recolored result is:

Blend[{GrayLevel[0.2], newColorHSB }, 0.4]
(* ===> RGBColor[0.1904, 0.2, 0.1904] *)


Note that by using the Method option, you can preserve or change different combinations of hue, saturation, and brightness before blending is done.