Search code examples
pythongradientlinear-interpolation

How to do linear interpolation with colors?


So I have an assignment where I have to replicate the image below using turtle. I know the basic concept of setting the pen to a color, then making a line, go 1 y coordinate down and repeat. But what I need to know is how do I know what color to make each line. I've heard about linear interpolation but I have no idea what that means.

assignment


Solution

  • Here's how you can do it with any starting and ending colors, without having to hard-code anything. Note that this is an example showing the operations done to each color channel; below I'll show how to do it in a more succinct way.

    # the starting color
    initial_color = (0.60156, 0, 0.99218)  # (154, 0, 254)
    
    # the final, target color
    target_color = (0.86328, 0.47656, 0.31250)  # (221, 122, 80)
    
    number_of_rows=10  # how many rows we're painting
    
    # get the total difference between each color channel
    red_difference=target_color[0]-initial_color[0]
    green_difference=target_color[1]-initial_color[1]
    blue_difference=target_color[2]-initial_color[2]
    
    # divide the difference by the number of rows, so each color changes by this amount per row
    red_delta = red_difference/number_of_rows
    green_delta = green_difference/number_of_rows
    blue_delta = blue_difference/number_of_rows
    
    # display the color for each row
    for i in range(0, number_of_rows):
        # apply the delta to the red, green and blue channels
        interpolated_color=(initial_color[0] + (red_delta * i), 
                            initial_color[1] + (green_delta * i),
                            initial_color[2] + (blue_delta * i))
        print(interpolated_color)
    

    Output:

    (0.60156, 0.0, 0.99218)
    (0.627732, 0.047656, 0.9242119999999999)
    (0.653904, 0.095312, 0.856244)
    (0.680076, 0.14296799999999998, 0.788276)
    (0.706248, 0.190624, 0.720308)
    (0.7324200000000001, 0.23828, 0.6523399999999999)
    (0.758592, 0.28593599999999997, 0.5843719999999999)
    (0.784764, 0.333592, 0.516404)
    (0.8109360000000001, 0.381248, 0.44843599999999995)
    (0.8371080000000001, 0.42890399999999995, 0.3804679999999999)
    

    Note that this stops before the final color, you can either use the target color for your last row, or just increase the range to number_of_rows + 1.

    Here's the above code but highly simplified - it gives the same output:

    # simpler version - we can skip the diffs and just get the deltas, and store all 3 colors in a list
    deltas=[(target_color[i] - initial_color[i])/number_of_rows for i in range(3)]
    for j in range(0, number_of_rows):
        interpolated_color=tuple([initial_color[i] + (deltas[i] * j) for i in range(3)])
        print(interpolated_color)