Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recreate colormap based on colorscale in matplotlib

I have an image of a color scale

enter image description here

I filter out the actual color scale by using

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading