# ColorReplace with thresholds and connected components

I would like to replace the colors in this drawing (called img) with colors of my choice. (For simplicity, we can assume my desired colors are ColorData["Rainbow"][i] for i = 0, .1, ..., 1.)

I have used DominantColors[img] to extract the principal colors and then used

ColorReplace[img, ...]


where the options are a list of associations, where White -> White and each of the remaining principal colors gets mapped to the Rainbow colors. Alas, because (I think) the distributions of colors are far from uniform, and because the edges of each line "blur" colors, the process never works. Each line in the drawing that should be a single color gets split.

I've tried ColorQuantize, ConnectedComponents, Erosion, Dilation, Sharpen, and EdgeDetection, in various forms, but never quite get what I seek.

I think I'm missing some image processing function that will sharpen each line and ensure each pixel is quantized to the proper color, but just can't find that function.

• I didn't know PrincipalColors , is it a new function in Mathematica 12.3? Jun 11 at 6:36

modified

With option ColorCoverage->0 you get six dominant colors.

colors = DominantColors[img, ColorCoverage -> 0]


Image with this colorspace follows to

imgN = ColorQuantize[img, colors]


Replace colors( Hue instead of ColorData["Rainbow"], shows more effect)

subst = MapIndexed[#1 -> Hue[#2[[1]]/Length[Rest[colors]]]&,Rest[colors]]
ColorReplace[imgN, subst]


ColorQuantize together with rainbow color selection returns image with the prescribed colors
imgR = ColorQuantize[img,Join[{White},Table[ColorData["Rainbow"][i], {i, 0.1, 1, .1}]]]

• Thanks so much ($\checkmark$). ColorCoverage was the key I was missing. (I had never heard of it.) Indeed, another lookup table besides "Rainbow" is superior, but I proposed that just for simplicity. Thanks so much. Jun 11 at 21:54