如何计算两种颜色之间的差异(亮度,亮度,颜色)?

时间:2011-06-10 14:39:23

标签: math colors brightness

我该如何计算

  • 光度对比度,
  • 亮度差异,
  • 颜色的差异
两种给定颜色之间的

示例:

输入

  • 颜色1:#99ccff
  • 颜色2:#225588

输出

  • 光度对比度:4.57:1
  • 亮度差异:119
  • 颜色差异:357

1 个答案:

答案 0 :(得分:1)

将每种颜色从(R,G,B)转换为(H,S,V)[或(H,S,L)]坐标。您可以找到公式at Wikipedia

我为此编写了Pascal函数:

function RGBToHSV(const Color: TRGB): THSV;
var
  cmax, cmin, cdiff: real;
begin
  cmax := MaxComponent(Color);
  cmin := MinComponent(Color);
  cdiff := cmax - cmin;

  with Color, result do
  begin

    // Hue
    if cmax = cmin then
      hsvHue := 0
    else if cmax = rgbRed then
      hsvHue := (60 * (rgbGreen - rgbBlue) / cdiff)
    else if cmax = rgbGreen then
      hsvHue := (60 * (rgbBlue - rgbRed) / cdiff) + 120
    else
      hsvHue := (60 * (rgbRed - rgbGreen) / cdiff) + 240;

    hsvHue := Fix360(hsvHue);

    // Saturation
    if cmax = 0 then
      hsvSaturation := 0
    else
      hsvSaturation := 1 - cmin / cmax;

    // Value
    hsvValue := cmax;

  end;

end;

function RGBToHSL(const Color: TRGB): THSL;
var
  cmax, cmin, cdiff, csum: real;
begin
  cmax := MaxComponent(Color);
  cmin := MinComponent(Color);
  cdiff := cmax - cmin;
  csum := cmax + cmin;

  with Color, result do
  begin

    // Hue
    if cmax = cmin then
      hslHue := 0
    else if cmax = rgbRed then
      hslHue := (60 * (rgbGreen - rgbBlue) / cdiff)
    else if cmax = rgbGreen then
      hslHue := (60 * (rgbBlue - rgbRed) / cdiff) + 120
    else
      hslHue := (60 * (rgbRed - rgbGreen) / cdiff) + 240;

    hslHue := Fix360(hslHue);

    // Saturation
    if cmax = cmin then
      hslSaturation := 0
    else if csum <= 1 then
      hslSaturation := cdiff / csum
    else
      hslSaturation := cdiff / (2 - csum);

    // Lightness
    hslLightness := csum / 2;

  end;

end;