Custom color maps

You can also apply custom color maps to an image. This functionality can be achieved in several ways.

The first approach is to define a color map that maps the 0 to 255 grayscale values to 256 colors. This can be done by creating an 8-bit color image of size 256 x 1 in order to store all the created colors. After that, you map the grayscale intensities of the image to the defined colors by means of a lookup table. In order to achieve this, you can do one of the following:

One key point is to store the created colors when creating the 8-bit color image of size 256 x 1. If you are going to use cv2.LUT(), the image should be created as follows:

lut = np.zeros((256, 3), dtype=np.uint8)

If you are going to use cv2.cv2.applyColorMap(), then it should be as follows:

lut = np.zeros((256, 1, 3), dtype=np.uint8)

The full code for this can be seen in color_map_custom_values.py. The output of this script can be seen in the following screenshot:

The second approach to define a color map is to provide only some key colors and then interpolate the values in order to get all the necessary colors to build the lookup table. The color_map_custom_key_colors.py script shows how to achieve this. 

The build_lut() function builds the lookup table based on these key colors. Based on five color points, this function calls np.linespace() to get all the 64 evenly spaced colors calculated over the interval, each defined by two color points. To understand this better, look at the following screenshot:

In this screenshot, you can see, for example, how to calculate all the 64 evenly spaced colors for two line segments (see the green and blue highlighted segments).

Finally,in order to build the lookup table for the following five key color points ((0, (0, 255, 128)), (0.25, (128, 184, 64)), (0.5, (255, 128, 0)), (0.75, (64, 128, 224)), and (1.0, (0, 128, 255))), the following calls to np.linespace() are performed:

blue : np.linspace('0', '128', '64' - '0' = '64')
green : np.linspace('255', '184', '64' - '0' = '64')
red : np.linspace('128', '64', '64' - '0' = '64')
blue : np.linspace('128', '255', '128' - '64' = '64')
green : np.linspace('184', '128', '128' - '64' = '64')
red : np.linspace('64', '0', '128' - '64' = '64')
blue : np.linspace('255', '64', '192' - '128' = '64')
green : np.linspace('128', '128', '192' - '128' = '64')
red : np.linspace('0', '224', '192' - '128' = '64')
blue : np.linspace('64', '0', '256' - '192' = '64')
green : np.linspace('128', '128', '256' - '192' = '64')
red : np.linspace('224', '255', '256' - '192' = '64')

The output of the color_map_custom_key_colors.py script can be seen in the next screenshot:

In the previous screenshot, you can see the effect of applying two custom color maps to a grayscale image.