Nik
Nik

Reputation: 5745

Python: convert values between 0 and 1 to color range red to blue

I know this is very similar to a previous question that I had posted, I cannot figure out how to modify it to suit this problem.

I have a array of values between 0 and 1. I want to convert these values to RGB color array ranging from red (0) to blue (1). The solution suggested in the previous question converted values to HSV tuples first, and then used colosys.hsv_to_rgb() to convert to RGB values.

This was fine if I wanted to generate colors between red and green. I could interpolate the hue value linearly. However, when the extreme colors are red and blue, the intermediary values take on green color because green hue lies between red and blue. Is there a way I can avoid this and get colors only in the vicinity of red and blue?

I know I can linearly interpolate RGB values directly, but that does not give a good color spectrum. So please tell me a solution using HSV space.

Upvotes: 4

Views: 4643

Answers (2)

AJMansfield
AJMansfield

Reputation: 4129

Hue is a cyclic value, thus, if you add the total hue range to any color's hue (modulo its max value, so that it is still within the range), you get the exact same color. So instead of increasing it from red to blue, decrease it from red to blue. HSV is a cylindrical color model.

enter image description here

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

Scale your 0-1 input to 0-(-120) output, take the modulus by 360, and use that as your hue (or 0-(-0.3333...) and 1.0 as appropriate).

Upvotes: 4

Related Questions