Skip to content

Instantly share code, notes, and snippets.

@StefRe
Last active September 25, 2024 11:54
Show Gist options
  • Save StefRe/5da8289a955d82ba74078d79ebc11d85 to your computer and use it in GitHub Desktop.
Save StefRe/5da8289a955d82ba74078d79ebc11d85 to your computer and use it in GitHub Desktop.
Use matplotlib colormap in OpenCV
def make_colormap_from_mpl(cm):
"""Create look-up table to convert grayscale to BGR-image.
The returned colormap can be used like
bgr_img = colormap[gray_img]
Args:
cm: Matplotlib colormap name, e.g. "autumn" or
colormap instance e.g. mpl.cm.autumn
Returns:
numpy array of shape (256, 3) with BGR ints
"""
if isinstance(cm, str):
import matplotlib as mpl
cm = mpl.colormaps[cm]
lut = cm(np.linspace(0, 1, 256))[...,:-1]
return (lut[..., [2,1,0]] * 255).astype(np.uint8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment