The Python Oracle

How to create a discrete RGB colourmap with N colours using numpy

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island

--

Chapters
00:00 Question
02:03 Accepted answer (Score 6)
02:46 Answer 2 (Score 1)
03:20 Thank you

--

Full question
https://stackoverflow.com/questions/5098...

Question links:
[image]: https://i.stack.imgur.com/5aWDC.png
[image]: https://i.stack.imgur.com/3XXnv.png
[image]: https://i.stack.imgur.com/oBPQZ.png
[image]: https://i.stack.imgur.com/AoB0e.png

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #numpy #colormap

#avk47



ACCEPTED ANSWER

Score 7


Here is one reasonably convenient method using np.clip:

def spec(N):                                             
    t = np.linspace(-510, 510, N)                                              
    return np.round(np.clip(np.stack([-t, 510-np.abs(t), t], axis=1), 0, 255)).astype(np.uint8)

It avoids the problem you describe by only relying on the only two points that are guaranteed to be on the grid for any N which are the first and last points.

Examples:

>>> spec(5)
array([[255,   0,   0],
       [255, 255,   0],
       [  0, 255,   0],
       [  0, 255, 255],
       [  0,   0, 255]], dtype=uint8)
>>> spec(10)
array([[255,   0,   0],
       [255, 113,   0],
       [255, 227,   0],
       [170, 255,   0],
       [ 57, 255,   0],
       [  0, 255,  57],
       [  0, 255, 170],
       [  0, 227, 255],
       [  0, 113, 255],
       [  0,   0, 255]], dtype=uint8)



ANSWER 2

Score 1


If you just want RGB at given levels, the diagram that you have posted itself serves as the answer -

R = [255] * 256
R.extend(list(reversed(range(256))))
R.extend([0] * 256)
R.extend([0] * 256)

G = list(range(256))
G.extend([255] * 256)
G.extend([255] * 256)
G.extend(list(reversed(range(256))))

B = [0] * 256
B.extend([0] * 256)
B.extend(list(range(256)))
B.extend([255] * 256)

level = 5
step = 1024 // (level -1)

print(R[::step])
print(G[::step])
print(B[::step])