Home > Backend Development > Golang > How Can I Find the Intermediate Color Between Two Given RGB Colors Using Python?

How Can I Find the Intermediate Color Between Two Given RGB Colors Using Python?

DDD
Release: 2024-12-08 16:45:14
Original
593 people have browsed it

How Can I Find the Intermediate Color Between Two Given RGB Colors Using Python?

Finding the Intermediate Color Between Painted Hues

When mixing paints, the resulting color is influenced by the absorption properties of the pigments. Blue paint absorbs red and green light, while yellow paint absorbs blue light. When combined, these pigments would theoretically produce a muddy gray or black. However, in practice, the bias of blue paint towards green often results in a muddy green hue.

Instead of simulating paint mixing, an algorithm for interpolating colors along a color wheel can provide intuitive results. The HSL (Hue, Saturation, Lightness) color space is particularly useful as it allows for the averaging of hues.

Python Implementation

The Python code below implements the interpolation algorithm:

from colorsys import rgb_to_hls,hls_to_rgb
from math import sin,cos,atan2,pi

def average_colors(rgb1, rgb2):
    h1, l1, s1 = rgb_to_hls(rgb1[0]/255., rgb1[1]/255., rgb1[2]/255.)
    h2, l2, s2 = rgb_to_hls(rgb2[0]/255., rgb2[1]/255., rgb2[2]/255.)
    s = 0.5 * (s1 + s2)
    l = 0.5 * (l1 + l2)
    x = cos(2*pi*h1) + cos(2*pi*h2)
    y = sin(2*pi*h1) + sin(2*pi*h2)
    if x != 0.0 or y != 0.0:
        h = atan2(y, x) / (2*pi)
    else:
        h = 0.0
        s = 0.0
    r, g, b = hls_to_rgb(h, l, s)
    return (int(r*255.), int(g*255.), int(b*255.))
Copy after login

Results

Using blue and yellow as input colors, the algorithm produces a green hue:

>>> average_colors((255,255,0),(0,0,255))
(0, 255, 111)
Copy after login

Mixing blue and cyan produces cyan:

>>> average_colors((255,255,0),(0,255,255))
(0, 255, 0)
Copy after login

Limitations

It is important to note that this algorithm does not accurately simulate paint mixing. Paint mixing involves the absorption of light, which is a more complex process. The HSL interpolation algorithm provides an intuitive mixing of colors that is not grounded in physical reality.

The above is the detailed content of How Can I Find the Intermediate Color Between Two Given RGB Colors Using Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template