Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply MatplotLib or custom colormap to OpenCV image

OpenCV has a limited amount of color maps. MatplotLib has many more color maps, but it is not straightforward to apply these colormaps to given OpenCV images. How to apply MatplotLib color maps from the page below to OpenCV images when using the Python API? This is similar to applying a custom colormap to a given image.

https://matplotlib.org/examples/color/colormaps_reference.html

like image 934
verified.human Avatar asked Sep 25 '18 12:09

verified.human


People also ask

What is Matplotlib colormap?

cmap stands for colormap and it's a colormap instance or registered colormap name (cmap will only work if c is an array of floats). Matplotlib colormaps are divided into the following categories: sequential, diverging, and qualitative.

What is Matplotlib default colormap?

Colormap. The new default colormap used by matplotlib. cm. ScalarMappable instances is 'viridis' (aka option D).

How does colormap work Python?

The format of the colormap is that each row contains three elements (red, green, blue) and the lower color limit is mapped to the first entry, the upper color limit is mapped to the last and data is mapped linearly to all colors that may appear in between the two.


1 Answers

For Python >= 2.7, cmapy packages this functionality in a convenient way. Install it with:

Python 2.7:

pip install cmapy

Python 3.x:

pip3 install cmapy

Or, for Anaconda (from conda-forge):

conda install -c conda-forge cmapy 

And use it like this:

import cv2
import matplotlib.pyplot as plt
import cmapy

# Read image.
img = cv2.imread('imgs/woman.png')

# Colorize.
img_colorized = cv2.applyColorMap(img, cmapy.cmap('viridis'))

# Display
plt.imshow(img_colorized)
plt.show()

Different colormaps give something like this:

See all the available colormaps in action here.

Disclaimer: I wrote cmapy (because I needed this functionality for another project), and internally, it does pretty much the same as the other answers.

like image 152
Milo Avatar answered Oct 13 '22 07:10

Milo