Recreate colormap based on colorscale in matplotlib

Viewed 26

I have an image of a color scale

enter image description here

I filter out the actual color scale by using

import cv2
import numpy as np

colorbar = cv2.imread('colorbar-scheme-elevation.png', cv2.IMREAD_UNCHANGED)
colorbar = cv2.cvtColor(colorbar, cv2.COLOR_BGRA2BGR)

hsv = cv2.cvtColor(colorbar, cv2.COLOR_RGB2HSV)
lower_gray = np.array([0, 0, 0])
upper_gray = np.array([255, 10, 255])

mask = cv2.inRange(hsv, lower_gray, upper_gray)
mask = cv2.bitwise_not(mask)
res = cv2.bitwise_and(colorbar, colorbar, mask=mask)
gray = cv2.cvtColor(res, cv2.COLOR_RGB2GRAY)


ret, thresh = cv2.threshold(gray, 10, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
c = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(c)

ROI = colorbar[y:y + h, x:x + w]

The end result looks as follows: enter image description here

Next, I only need one row

ROI = ROI[0]

All the unique colors can be found using

unique_colors = list(reversed(np.unique(ROI, axis=0)))

How can I recreate the color scale with the unique color-values?

1 Answers

You can create a Matplotlib colormap starting from a list of colors with ListedColormap (note that I didn't consider your last two commands):

from matplotlib.colors import ListedColormap
cmap = ListedColormap(ROI[0].astype(float) / 255)
Related