mike
mike

Reputation: 5055

Map integer to color in rainbow spectrum

I want to color k clusters of points in a 2D grid. Right now I using a naive approach.

I'm using RGB to set a color, the G component is fix, R is counted down gradually, B is counted up gradually. So the first cluster has R set to 255 and the last to 0, vice versa for B.

int r = 255, g = 80, b = 0;
// do stuff
int step = 255 / k;
// loop over data
int cluster = getCurrentCluster();
int currentR = r - (cluster * step);
int currentG = g;
int currentB = b + (cluster * step);

The current solution is working and effektive. It's possible to differentiate the clusters by colors

colored voronoi cells that show result of cluster analysis with k-means clustering. K is set to 30, number of elements is 5M, image dimension is square with 1M pixels

But I don't like it, and would prefer rainbow colors or at least a richer spectrum.

How can I achieve that? How can I map an integer in interval [0, k) to a color that meets my requirements?

Another approach that came to my mind was to map the integer to a wave length in a given interval, e.g. 400 nm to 800 nm (should roughly be the rainbow spectrum, if I recall correctly) and convert the wavelength to RGB.

Upvotes: 2

Views: 2159

Answers (2)

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77474

HSV will give the nicest results, but needs trigonometry.

Instead, consider three functions:

  1. R: r = x < 256 ? 255 - x : x < 512 ? 0 : x - 512
  2. G: g = x < 256 ? x : x < 512 ? 512 - x : 0
  3. B: b = x < 256 ? 0 : x < 512 ? x - 256 : 768 - x

These may be easier and faster, although less aestethically pleasing (not so a nice yellow, orange, etc.)

Upvotes: 1

marom
marom

Reputation: 5230

If you want to map a linear range to a rainbow like spectrum then you are better off starting with a color space like HSV and then convert to RGB.

Here you find the details of the conversion

Upvotes: 4

Related Questions