I would start with a set brightness 100% and go around primary colors first:
FF0000, 00FF00, 0000FF
then the combinations
FFFF00, FF00FF, 00FFFF
next for example halve the brightness and do same round. There's not too many really clearly distinct colors, after these I would start to vary the line width and do dotted/dashed lines etc.
Straightforward to program and gives you fairly distinct colours.
EDIT: Request for code sample
Also - adding in the additional pattern as below if gray is an acceptable colour:
255, 255, 255
128, 128, 128
There are a number of ways you can handle generating these in code.
The Easy Way
If you can guarantee that you will never need more than a fixed number of colours, just generate an array of colours following this pattern and use those:
If you don't know how many colours you are going to need, the code below will generate up to 896 colours using this pattern. (896 = 256 * 7 / 2) 256 is the colour space per channel, we have 7 patterns and we stop before we get to colours separated by only 1 colour value.
I've probably made harder work of this code than I needed to. First, there is an intensity generator which starts at 255, then generates the values as per the pattern described above. The pattern generator just loops through the seven colour patterns.
using System;
class Program {
static void Main(string[] args) {
ColourGenerator generator = new ColourGenerator();
for (int i = 0; i < 896; i++) {
Console.WriteLine(string.Format("{0}: {1}", i, generator.NextColour()));
}
}
}
public class ColourGenerator {
private int index = 0;
private IntensityGenerator intensityGenerator = new IntensityGenerator();
public string NextColour() {
string colour = string.Format(PatternGenerator.NextPattern(index),
intensityGenerator.NextIntensity(index));
index++;
return colour;
}
}
public class PatternGenerator {
public static string NextPattern(int index) {
switch (index % 7) {
case 0: return "{0}0000";
case 1: return "00{0}00";
case 2: return "0000{0}";
case 3: return "{0}{0}00";
case 4: return "{0}00{0}";
case 5: return "00{0}{0}";
case 6: return "{0}{0}{0}";
default: throw new Exception("Math error");
}
}
}
public class IntensityGenerator {
private IntensityValueWalker walker;
private int current;
public string NextIntensity(int index) {
if (index == 0) {
current = 255;
}
else if (index % 7 == 0) {
if (walker == null) {
walker = new IntensityValueWalker();
}
else {
walker.MoveNext();
}
current = walker.Current.Value;
}
string currentText = current.ToString("X");
if (currentText.Length == 1) currentText = "0" + currentText;
return currentText;
}
}
public class IntensityValue {
private IntensityValue mChildA;
private IntensityValue mChildB;
public IntensityValue(IntensityValue parent, int value, int level) {
if (level > 7) throw new Exception("There are no more colours left");
Value = value;
Parent = parent;
Level = level;
}
public int Level { get; set; }
public int Value { get; set; }
public IntensityValue Parent { get; set; }
public IntensityValue ChildA {
get {
return mChildA ?? (mChildA = new IntensityValue(this, this.Value - (1<<(7-Level)), Level+1));
}
}
public IntensityValue ChildB {
get {
return mChildB ?? (mChildB = new IntensityValue(this, Value + (1<<(7-Level)), Level+1));
}
}
}
public class IntensityValueWalker {
public IntensityValueWalker() {
Current = new IntensityValue(null, 1<<7, 1);
}
public IntensityValue Current { get; set; }
public void MoveNext() {
if (Current.Parent == null) {
Current = Current.ChildA;
}
else if (Current.Parent.ChildA == Current) {
Current = Current.Parent.ChildB;
}
else {
int levelsUp = 1;
Current = Current.Parent;
while (Current.Parent != null && Current == Current.Parent.ChildB) {
Current = Current.Parent;
levelsUp++;
}
if (Current.Parent != null) {
Current = Current.Parent.ChildB;
}
else {
levelsUp++;
}
for (int i = 0; i < levelsUp; i++) {
Current = Current.ChildA;
}
}
}
}
You could get a random set of your 3 255 values and check it against the last set of 3 values, making sure they are each at least X away from the old values before using them.
OLD: 190, 120, 100
NEW: 180, 200, 30
If X = 20, then the new set would be regenerated again.
I think the HSV (or HSL) space has more opportunities here. If you don't mind the extra conversion, it's pretty easy to go through all the colors by just rotating the Hue value. If that's not enough, you can change the Saturation/Value/Lightness values and go through the rotation again. Or, you can always shift the Hue values or change your "stepping" angle and rotate more times.
You could also think of the color space as all combinations of three numbers from 0 to 255, inclusive. That's the base-255 representation of a number between 0 and 255^3, forced to have three decimal places (add zeros on to the end if need be.)
So to generate x number of colors, you'd calculate x evenly spaced percentages, 0 to 100. Get numbers by multiplying those percentages by 255^3, convert those numbers to base 255, and add zeros as previously mentioned.
Base conversion algorithm, for reference (in pseudocode that's quite close to C#):
int num = (number to convert);
int baseConvert = (desired base, 255 in this case);
(array of ints) nums = new (array of ints);
int x = num;
double digits = Math.Log(num, baseConvert); //or ln(num) / ln(baseConvert)
int numDigits = (digits - Math.Ceiling(digits) == 0 ? (int)(digits + 1) : (int)Math.Ceiling(digits)); //go up one if it turns out even
for (int i = 0; i < numDigits; i++)
{
int toAdd = ((int)Math.Floor(x / Math.Pow((double)convertBase, (double)(numDigits - i - 1))));
//Formula for 0th digit: d = num / (convertBase^(numDigits - 1))
//Then subtract (d * convertBase^(numDigits - 1)) from the num and continue
nums.Add(toAdd);
x -= toAdd * (int)Math.Pow((double)convertBase, (double)(numDigits - i - 1));
}
return nums;
You might also have to do something to bring the range in a little bit, to avoid having white and black, if you want. Those numbers aren't actually a smooth color scale, but they'll generate separate colors if you don't have too many.
There's a flaw in the previous RGB solutions. They don't take advantage of the whole color space since they use a color value and 0 for the channels:
#006600
#330000
#FF00FF
Instead they should be using all the possible color values to generate mixed colors that can have up to 3 different values across the color channels:
#336600
#FF0066
#33FF66
Using the full color space you can generate more distinct colors. For example, if you have 4 values per channel, then 4*4*4=64 colors can be generated. With the other scheme, only 4*7+1=29 colors can be generated.
If you want N colors, then the number of values per channel required is: ceil(cube_root(N))
With that, you can then determine the possible (0-255 range) values (python):
max = 255
segs = int(num**(Decimal("1.0")/3))
step = int(max/segs)
p = [(i*step) for i in xrange(segs)]
values = [max]
values.extend(p)
Then you can iterate over the RGB colors (this is not recommended):
total = 0
for red in values:
for green in values:
for blue in values:
if total <= N:
print color(red, green, blue)
total += 1
Nested loops will work, but are not recommended since it will favor the blue channel and the resulting colors will not have enough red (N will most likely be less than the number of all possible color values).
You can create a better algorithm for the loops where each channel is treated equally and more distinct color values are favored over small ones.
I have a solution, but didn't want to post it since it isn't the easiest to understand or efficient. But, you can view the solution if you really want to.
Here is a sample of 64 generated colors: 64 colors
The final tab of the page allows you to sort the values in several ways, and then interleave them (ordered shuffle) so that you get very distinct colors placed next to one another.
As of this writing, it only works well in Chrome and Safari, with a shim for Firefox; it uses HTML5 range input sliders in the interface, which IE9 and Firefox do not yet support natively.
To implement a variation list where by your colors go, 255 then use all possibilities of that up, then add 0 and all RGB patterns with those two values. Then add 128 and all RGB combinations with those. Then 64. Then 192. Etc.
In Java,
public Color getColor(int i) {
return new Color(getRGB(i));
}
public int getRGB(int index) {
int[] p = getPattern(index);
return getElement(p[0]) << 16 | getElement(p[1]) << 8 | getElement(p[2]);
}
public int getElement(int index) {
int value = index - 1;
int v = 0;
for (int i = 0; i < 8; i++) {
v = v | (value & 1);
v <<= 1;
value >>= 1;
}
v >>= 1;
return v & 0xFF;
}
public int[] getPattern(int index) {
int n = (int)Math.cbrt(index);
index -= (n*n*n);
int[] p = new int[3];
Arrays.fill(p,n);
if (index == 0) {
return p;
}
index--;
int v = index % 3;
index = index / 3;
if (index < n) {
p[v] = index % n;
return p;
}
index -= n;
p[v ] = index / n;
p[++v % 3] = index % n;
return p;
}
This will produce patterns of that type infinitely (2^24) into the future. However, after a hundred or so spots you likely won't see much of a difference between a color with 0 or 32 in the blue's place.
You might be better off normalizing this into a different color space. LAB color space for example with the L,A,B values normalized and converted. So the distinctness of the color is pushed through something more akin to the human eye.
getElement() reverses the endian of an 8 bit number, and starts counting from -1 rather than 0 (masking with 255). So it goes 255,0,127,192,64,... as the number grows it moves less and less significant bits, subdividing the number.
getPattern() determines what the most significant element in the pattern should be (it's the cube root). Then proceeds to break down the 3N²+3N+1 different patterns that involve that most significant element.
Read left to right, top to bottom. 729 colors (9³). So all the patterns up to n = 9. You'll notice the speed at which they start to clash. There's only so many WRGBCYMK variations. And this solution, while clever basically only does different shades of primary colors.
Much of the clashing is due to green and how similar most greens look to most people. The demand that each be maximally different at start rather than just different enough to not be the same color. And basic flaws in the idea resulting in primary colors patterns, and identical hues.
Using CIELab2000 Color Space and Distance Routine to randomly select and try 10k different colors and find the maximally-distant minimum-distance from previous colors, (pretty much the definition of the request) avoids clashing longer than the above solution:
Which could be just called a static list for the Easy Way. It took an hour and a half to generate 729 entries:
Using brute force to (testing all 16,777,216 RGB colors through CIELab Delta2000 / Starting with black) produces a series. Which starts to clash at around 26 but could make it to 30 or 40 with visual inspection and manual dropping (which can't be done with a computer). So doing the absolute maximum one can programmatically only makes a couple dozen distinct colors. A discrete list is your best bet. You will get more discrete colors with a list than you would programmatically. The easy way is the best solution, start mixing and matching with other ways to alter your data than color.
for getting nth colour. Just this kind of code would be enough. This i have use in my opencv clustering problem. This will create different colours as col changes.
for(int col=1;col<CLUSTER_COUNT+1;col++){
switch(col%6)
{
case 1:cout<<Scalar(0,0,(int)(255/(int)(col/6+1)))<<endl;break;
case 2:cout<<Scalar(0,(int)(255/(int)(col/6+1)),0)<<endl;break;
case 3:cout<<Scalar((int)(255/(int)(col/6+1)),0,0)<<endl;break;
case 4:cout<<Scalar(0,(int)(255/(int)(col/6+1)),(int)(255/(int)(col/6+1)))<<endl;break;
case 5:cout<<Scalar((int)(255/(int)(col/6+1)),0,(int)(255/(int)(col/6+1)))<<endl;break;
case 0:cout<<Scalar((int)(255/(int)(col/6)),(int)(255/(int)(col/6)),0)<<endl;break;
}
}
I needed the same functionality, in a simple form.
What I needed was to generate as unique as possible colors from an an increasing index value.
Here is the code, in C# (Any other language implementation should be very similar)
The mechanism is very simple
A pattern of color_writers get generated from indexA values from 0 to 7.
For indices < 8, those colors are = color_writer[indexA] * 255.
For indices between 8 and 15, those colors are = color_writer[indexA] * 255 + (color_writer[indexA+1]) * 127
For indices between 16 and 23, those colors are = color_writer[indexA] * 255 + (color_writer[indexA+1]) * 127 + (color_writer[indexA+2]) * 63
And so on:
private System.Drawing.Color GetRandColor(int index)
{
byte red = 0;
byte green = 0;
byte blue = 0;
for (int t = 0; t <= index / 8; t++)
{
int index_a = (index+t) % 8;
int index_b = index_a / 2;
//Color writers, take on values of 0 and 1
int color_red = index_a % 2;
int color_blue = index_b % 2;
int color_green = ((index_b + 1) % 3) % 2;
int add = 255 / (t + 1);
red = (byte)(red+color_red * add);
green = (byte)(green + color_green * add);
blue = (byte)(blue + color_blue * add);
}
Color color = Color.FromArgb(red, green, blue);
return color;
}
Note: To avoid generating bright and hard to see colors (in this example: yellow on white background) you can modify it with a recursive loop:
int skip_index = 0;
private System.Drawing.Color GetRandColor(int index)
{
index += skip_index;
byte red = 0;
byte green = 0;
byte blue = 0;
for (int t = 0; t <= index / 8; t++)
{
int index_a = (index+t) % 8;
int index_b = index_a / 2;
//Color writers, take on values of 0 and 1
int color_red = index_a % 2;
int color_blue = index_b % 2;
int color_green = ((index_b + 1) % 3) % 2;
int add = 255 / (t + 1);
red = (byte)(red + color_red * add);
green = (byte)(green + color_green * add);
blue = (byte)(blue + color_blue * add);
}
if(red > 200 && green > 200)
{
skip_index++;
return GetRandColor(index);
}
Color color = Color.FromArgb(red, green, blue);
return color;
}