For the record, I am very bad at Python. Yet, it has become more and more my go-to language for doing little things that aren’t web. For instance, I recently undertook to create a color picker/color wheel in Python.
For the uninitiated, a color wheel or color spectrum is a series of hues that run from red to indigo (roughly purple to our eyes). It’s the rainbow. The color wheel is this same thing but wrapped around in a way that shows all the hues the human eye can see. In reality, indigo doesn’t converge on red as you go up in light frequency, but the hues that you would see if it did are colors we know well — magenta/pink.
So, generating a color wheel is an interesting challenge. The primary colors can be created from the hex colors 0xff0000 (red), 0x00ff00 (green), and 0x0000ff (blue). You probably see the pattern easily. A color breaks down into three channels, each of which has up to 0xff or 256 values from 0, completely absent, to 0xff, completely displayed. Blending from blue to green implies moving from 0x00ff00 to 0x0000ff by decrementing the green channel monotonically as you monotonically increment the blue channel. So, you can probably start to see how the logic for generating the color spectrum graphic will have to work. Of course I’m ignoring a few colors that are important. Red, green, and blue are only half the colors that are necessary for the color wheel to look complete. The others are 0x00ffff (cyan), magenta (0xff00ff), and yellow (0xffff00). These colors appear in color spectrum interwoven between the primary colors. If you’re wondering why red and green make yellow, you’ll probably want to read about Color by Addition. Though, from a numbers perspective it’s easy to see a relationship between 0xff0000 -> 0xffff00 -> 0x00ff00.
Creating the gamut requires calculating how much of each color to use in the blending. One important aspect of a color wheel is that any color you can select is a blend of at most two colors. So, one way to generate a color wheel is to go pixel-by-pixel through the image you want to create figuring out what sextant you’re in, deciding which color you’re closest to, then figuring out how much of the other color to blend into it. That’s the approach I took. It’s true that you can do this other ways. In fact, I’m pretty sure there is a slick algorithm for this that I didn’t realize. I was on a plane when I wrote this and consider it more about learning Python than about making the most compact implementation of color spectrum generation.
Anyway, here’s the code (using the Python Image Library) on GitHub.