Mostafa
Mostafa

Reputation: 51

Create corresponding RGB list (colormap) based on values in another list

I am working with a 3D pointcloud colorizing in python.

Basically, I have a list of points, each point has a certain value of depth (distance). I want to create a corresponding RGB list values based on this distance values.

Example of 10 points:

distance_list = [0.1, 0.3, 0.4, 0.5, 1.2, 6, 8.1, 0.9, 5, 0.7]

What I want to have, is a list of RGB values (colormap) between Red and Blue, or any other 2 colors, with these values corresponds to the distance, so Red is the closest, while blue is the furthest point.

So more or less, I would have something like

rgb_list = [(255, 0, 0), (R2, G2, B2), (R3, G3, B3), (R4, G4, B4), (R5, G5, B5), (R6, G6, B6), (0, 0, 255), (R8, G8, B8), (R9, G9, B9), (R10, G10, B10)]

I tried using ready made colormaps from matplotlib, but I fail to customize it based on values which I have, and extract the RGB values out of it.

Upvotes: 5

Views: 5953

Answers (1)

Derek O
Derek O

Reputation: 19565

matplotlib has built-in colormaps that are normalized between 0 and 1, but we can make the colormap conform to your data by normalizing the colormap to the minimum and maximum values of your distance_list.

The variable color_list contains every color that your distances correspond to if you need it, and you can see that your data can be mapped directly to the tick marks on the colorbar.

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cm as cm

distance_list = [0.1, 0.3, 0.4, 0.5, 1.2, 6, 8.1, 0.9, 5, 0.7]

min_val, max_val = min(distance_list), max(distance_list)

# use the coolwarm colormap that is built-in, and goes from blue to red
cmap = mpl.cm.coolwarm
norm = mpl.colors.Normalize(vmin=min_val, vmax=max_val)

# convert your distances to color coordinates
color_list = cmap(distance_list)

fig, ax = plt.subplots()
cb = mpl.colorbar.ColorbarBase(ax, cmap=cmap, norm=norm, ticks = sorted(distance_list), orientation='horizontal')
cb.set_label('Distance (least to greatest)')
ax.tick_params(axis='x', rotation=90)

plt.show()

enter image description here

> color_list
array([[0.34832334, 0.46571115, 0.88834616, 1.        ],
       [0.61931795, 0.74412073, 0.99893092, 1.        ],
       [0.75361062, 0.83023285, 0.96087116, 1.        ],
       [0.86742764, 0.8643766 , 0.86260246, 1.        ],
       [0.70567316, 0.01555616, 0.15023281, 1.        ],
       [0.70567316, 0.01555616, 0.15023281, 1.        ],
       [0.70567316, 0.01555616, 0.15023281, 1.        ],
       [0.83936494, 0.32185622, 0.26492398, 1.        ],
       [0.70567316, 0.01555616, 0.15023281, 1.        ],
       [0.96849975, 0.67397738, 0.55664926, 1.        ]])

Upvotes: 3

Related Questions