How to create a discrete RGB colourmap with N colours using numpy
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles
--
Chapters
00:00 How To Create A Discrete Rgb Colourmap With N Colours Using Numpy
01:28 Accepted Answer Score 7
02:02 Answer 2 Score 1
02:21 Thank you
--
Full question
https://stackoverflow.com/questions/5098...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #numpy #colormap
#avk47
    Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles
--
Chapters
00:00 How To Create A Discrete Rgb Colourmap With N Colours Using Numpy
01:28 Accepted Answer Score 7
02:02 Answer 2 Score 1
02:21 Thank you
--
Full question
https://stackoverflow.com/questions/5098...
--
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])