Python - Implement RGB calculation of gradient color

1. What problem was solved:

Find the RGB of the color gradient between two colors.

2. Formula:

Gradient = A + (B-A) / Step * N
In order to improve efficiency and avoid floating-point operations during programming, the division is often placed at the end, so the formula becomes:Gradient = A + (B-A) * N / Step

Note : Gradient represents the R/G/B value of the Nth step, and A, B, and Step represent the gradient from color A to color B in Steps.

3. Calculation process:

Set Step=3, change the RGB(200,50,0) color gradient to RGB(50,200,0), that is: RGB(200,50,0) changes to RGB(50,200,0) after 3 color gradients

The 0th conversion, which is RGB(200,50,0) itself:
R0 = 200 + (50 - 200) / 3 * 0 = 200
G0 = 50 + (200 - 50) / 3 * 0 = 50
B0 = 0 + (0 - 0) / 3 * 0 = 0
RGB0 = (200, 50, 0)

1st conversion:
R1 = 200 + (50 - 200) / 3 * 1 = 150
G1 = 50 + (200 - 50) / 3 * 1 = 100
B1 = 0 + (0 - 0) / 3 * 1 = 0
RGB1 = (150, 100, 0)

2nd conversion:
R2 = 200 + (50 - 200) / 3 * 2 = 100
G2 = 50 + (200 - 50) / 3 * 2 = 150
B2 = 0 + (0 - 0) / 3 * 2 = 0
RBG2 = (100, 150, 0)

The third conversion, that is, the target color RGB(50,200,0):
R3 = 200 + (50 - 200) / 3 * 3 = 50
G3 = 50 + (200 - 50) / 3 * 3 = 200
B3 = 0 + ( 0 - 0) / 3 * 3 = 0
RBG3 = (50, 200, 0)

4. Code

import matplotlib.pyplot as plt
import numpy as np

step = 3   # 经过step步到达目标颜色
color_num = step + 1
one = np.ones(color_num)
from_rgb = (200,50,0)  # 起始颜色
to_rbg = (50,200,0)    # 目标颜色

colors = [((from_rgb[0] + (to_rbg[0]-from_rgb[0])/step*i),
          (from_rgb[1] + (to_rbg[1]-from_rgb[1])/step*i),
          (from_rgb[2] + (to_rbg[2]-from_rgb[2])/step*i))
          for i in range(color_num)]
          
for index, color in enumerate(colors):
    print(index, color)

colors = [((from_rgb[0] + (to_rbg[0]-from_rgb[0])/step*i) / 255,
          (from_rgb[1] + (to_rbg[1]-from_rgb[1])/step*i) / 255,
          (from_rgb[2] + (to_rbg[2]-from_rgb[2])/step*i) / 255)
          for i in range(color_num)]

plt.pie(one, labels=range(color_num), colors=colors)  # colors要求是0-1的浮点数
plt.show()

Results and color display:
insert image description here

Five, draw inferences about other cases from one instance

Next, modify the step, starting color, and target color , and subdivide the display of changes in more steps.

例1:
step = 50
from_rgb = (193, 214, 6)
to_rbg = (244, 225, 67)
insert image description here


例2:
step = 50
from_rgb = (244, 225, 67)
to_rbg = (227, 118, 0)
insert image description here

6. Reference

  1. RGB calculation of color gradient

Guess you like

Origin blog.csdn.net/DreamingBetter/article/details/126872234