Athreya Daniel
Athreya Daniel

Reputation: 17

How to map a range of numbers to RGB in Python

I want to map a range of numbers from 0-3 to rgb colors.

I have seen posts like this one: Map a range of values (e.g. [0,255]) to a range of colours (e.g. rainbow: [red,blue]) in JavaScript but I don't know how to convert it to python and use it in my case.

I would like for the output to be the rgb value for the specific number between 0 and 3. Any help appreciated.

Upvotes: 1

Views: 3320

Answers (1)

Jay Mody
Jay Mody

Reputation: 4073

You could convert this answer from the post you linked into python:

import math

def num_to_rgb(val, max_val=3):
    i = (val * 255 / max_val);
    r = round(math.sin(0.024 * i + 0) * 127 + 128);
    g = round(math.sin(0.024 * i + 2) * 127 + 128);
    b = round(math.sin(0.024 * i + 4) * 127 + 128);
    return (r,g,b)

print(num_to_rgb(1.32))
>> (183, 1, 179)

this will return a tuple of three integers (r,g,b).

It is also a good idea to to make sure invalid inputs aren't allowed (aka negatives, or val > max_val):

def num_to_rgb(val, max_val=3):
    if (val > max_val):
        raise ValueError("val must not be greater than max_val")
    if (val < 0 or max_val < 0):
        raise ValueError("arguments may not be negative")

    i = (val * 255 / max_val);
    r = round(math.sin(0.024 * i + 0) * 127 + 128);
    g = round(math.sin(0.024 * i + 2) * 127 + 128);
    b = round(math.sin(0.024 * i + 4) * 127 + 128);
    return (r,g,b)

print(num_to_rgb(4.32))
>> ValueError: val must not be greater than max_val

Upvotes: 1

Related Questions