Implementação do CIEDE2000 em F#
| Número de visitas | 428 |
|---|---|
| Número de arquivos visualizados | 257 + 380 |
Esta página apresenta uma implementação de referência da fórmula de diferença de cor CIEDE2000 em F#. Se quiser assegurar uma compatibilidade perfeita (até à décima casa decimal) com algumas implementações de terceiros, poderá ter de modificar os comentários no código fonte. Para facilitar isto, a seguinte ligação automatiza esta operação.
A função ΔE2000 em F#
Consideremos a mais comum e académica (Sharma, 2005) das duas formulações.
// This function written in F# is not affiliated with the CIE (International Commission on Illumination),
// and is released into the public domain. It is provided "as is" without any warranty, express or implied.
open System
// The classic CIE ΔE2000 implementation, which operates on two L*a*b* colors, and returns their difference.
// "l" ranges from 0 to 100, while "a" and "b" are unbounded and commonly clamped to the range of -128 to 127.
let ciede_2000 (l_1: float) (a_1: float) (b_1: float) (l_2: float) (a_2: float) (b_2: float) : float =
// Working in F# with the CIEDE2000 color-difference formula.
// k_l, k_c, k_h are parametric factors to be adjusted according to
// different viewing parameters such as textures, backgrounds...
let k_l = 1.0
let k_c = 1.0
let k_h = 1.0
let mutable n = (Math.Sqrt(a_1 * a_1 + b_1 * b_1) + Math.Sqrt(a_2 * a_2 + b_2 * b_2)) * 0.5
n <- n * n * n * n * n * n * n
// A factor involving chroma raised to the power of 7 designed to make
// the influence of chroma on the total color difference more accurate.
n <- 1.0 + 0.5 * (1.0 - Math.Sqrt(n / (n + 6103515625.0)))
// Application of the chroma correction factor.
let c_1 = Math.Sqrt(a_1 * a_1 * n * n + b_1 * b_1)
let c_2 = Math.Sqrt(a_2 * a_2 * n * n + b_2 * b_2)
// atan2 is preferred over atan because it accurately computes the angle of
// a point (x, y) in all quadrants, handling the signs of both coordinates.
let mutable h_1 = Math.Atan2(b_1, a_1 * n)
let mutable h_2 = Math.Atan2(b_2, a_2 * n)
if h_1 < 0.0 then h_1 <- h_1 + 2.0 * Math.PI
if h_2 < 0.0 then h_2 <- h_2 + 2.0 * Math.PI
n <- Math.Abs(h_2 - h_1)
// Cross-implementation consistent rounding.
if Math.PI - 1E-14 < n && n < Math.PI + 1E-14 then n <- Math.PI
// When the hue angles lie in different quadrants, the straightforward
// average can produce a mean that incorrectly suggests a hue angle in
// the wrong quadrant, the next lines handle this issue.
let mutable h_m = (h_1 + h_2) * 0.5
let mutable h_d = (h_2 - h_1) * 0.5
if Math.PI < n then
h_d <- h_d + Math.PI
// 📜 Sharma’s formulation doesn’t use the next line, but the one after it,
// and these two variants differ by ±0.0003 on the final color differences.
h_m <- h_m + Math.PI
// h_m <- h_m + (if h_m < Math.PI then Math.PI else -Math.PI)
let p = 36.0 * h_m - 55.0 * Math.PI
n <- (c_1 + c_2) * 0.5
n <- n * n * n * n * n * n * n
// The hue rotation correction term is designed to account for the
// non-linear behavior of hue differences in the blue region.
let r_t = -2.0 * Math.Sqrt(n / (n + 6103515625.0))
* Math.Sin(Math.PI / 3.0 * Math.Exp(p * p / (-25.0 * Math.PI * Math.PI)))
n <- (l_1 + l_2) * 0.5
n <- (n - 50.0) * (n - 50.0)
// Lightness.
let l = (l_2 - l_1) / (k_l * (1.0 + 0.015 * n / Math.Sqrt(20.0 + n)))
// These coefficients adjust the impact of different harmonic
// components on the hue difference calculation.
let t = 1.0 + 0.24 * Math.Sin(2.0 * h_m + Math.PI / 2.0)
+ 0.32 * Math.Sin(3.0 * h_m + 8.0 * Math.PI / 15.0)
- 0.17 * Math.Sin(h_m + Math.PI / 3.0)
- 0.20 * Math.Sin(4.0 * h_m + 3.0 * Math.PI / 20.0)
n <- c_1 + c_2
// Hue.
let h = 2.0 * Math.Sqrt(c_1 * c_2) * Math.Sin(h_d) / (k_h * (1.0 + 0.0075 * n * t))
// Chroma.
let c = (c_2 - c_1) / (k_c * (1.0 + 0.0225 * n))
// Returning the square root ensures that dE00 accurately reflects the
// geometric distance in color space, which can range from 0 to around 185.
Math.Sqrt(l * l + h * h + c * c + c * h * r_t)
// GitHub Project : https://github.com/michel-leonard/ciede2000-color-matching
// Online Tests : https://michel-leonard.github.io/ciede2000-color-matching
// L1 = 79.1 a1 = 50.5 b1 = 2.2
// L2 = 78.5 a2 = 44.8 b2 = -1.9
// CIE ΔE00 = 2.8082542128 (Bruce Lindbloom, Netflix’s VMAF, ...)
// CIE ΔE00 = 2.8082675897 (Gaurav Sharma, OpenJDK, ...)
// Deviation between implementations ≈ 1.3e-5
// See the source code comments for easy switching between these two widely used ΔE*00 implementation variants.Parâmetros k_l, k_c e k_h
Os parâmetros k_l, k_c e k_h na fórmula CIEDE2000 são factores de ponderação aplicados aos componentes de brilho (ΔL*), croma (ΔC*) e matiz (ΔH*), respetivamente. São definidos como constantes no código fonte. No código-fonte, são definidos como constantes com um valor por defeito de 1, que corresponde às condições de observação padrão estabelecidas pela Comissão Internacional da Iluminação (CIE). Na prática, pode ser necessário ajustar estes coeficientes para refletir condições específicas: por exemplo, k_l = 2 é por vezes utilizado para dar mais peso a diferenças de brilho (uma ocorrência comum na indústria têxtil), enquanto k_c ou k_h podem ser reduzidos para aumentar a tolerância a variações de saturação ou matiz. Em resumo, estes coeficientes variam normalmente entre 0,5 e 2, sendo 1 o valor mais comum.
Precisão e fiabilidade do código fonte
A diferença entre a formulação académica de Sharma e a formulação simplificada de Lindbloom não excede ±0,0003 no ΔE2000 final. Isto corresponde à diferença normalmente medida entre duas implementações de 32 bits e é impercetível ao olho humano. As nossas implementações de 64 bits, todas consistentes entre si, garantem pelo menos 10 casas decimais corretas, pelo que a escolha de uma formulação em detrimento de outra é um pormenor técnico. A fórmula predefinida nesta página é a mais frequentemente apresentada na comunidade, é ligeiramente mais fácil de vetorizar.
✎ Se verificar que os comentários no código-fonte não coincidem com os comentários em inglês, informe o autor da página para que tal possa ser corrigido.
Como é que se convertem cores RGB em L*a*b*?
Vá para a página AWK, C, Dart, Java, JavaScript, Kotlin, Lua, PHP, Python, Ruby ou Rust onde esse conversor (utilizando o iluminante D65) já está implementado para além da função de comparação de cores.
Intervalos de valores no CIELAB e interpretação do ΔE2000
No espaço de cor CIELAB, o componente L* representa a luminosidade e normalmente varia de 0 (preto) a 100 (branco). Os componentes a* e b* representam os eixos de cor: a* vai do verde ao vermelho, enquanto b* vai do azul ao amarelo. Na prática, os valores de a* e b* estão quase sempre limitados a um intervalo entre -128 e +127, embora a norma não especifique um limite oficial para estes dois componentes.
| Cor 1 | Cor 2 | Valor de ΔE2000 |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 |
| Cor 1 | Cor 2 | Valor de ΔE2000 |
|---|---|---|
| 5 | ||
| 10 | ||
| 15 |
ΔE2000 (CIEDE2000) mede a diferença perceptível entre duas cores: 0 significa cores idênticas, e valores maiores (até 185 e mais) indicam uma diferença mais significativa. Por exemplo, um valor ΔE2000 em torno de 5 indica cores próximas, enquanto em torno de 15 indica cores claramente diferentes. Quando o valor ΔE2000 ultrapassa 40, as cores comparadas já não têm praticamente nada em comum, e não é possível obter informações precisas a partir delas.
Exemplo de utilização em F#
// Compute the Delta E (CIEDE2000) color difference between two L*a*b* colors in F#
let l1, a1, b1 = 3.9, 16.9, -4.9
let l2, a2, b2 = 3.1, 11.8, 3.6
let deltaE = ciede_2000 l1 a1 b1 l2 a2 b2
printfn "%f" deltaE
// .................................................. This shows a ΔE2000 of 7.0799401968
// As explained in the comments, compliance with Gaurav Sharma would display 7.0799265161Resultados dos testes
O nosso programa de testes, escrito em C99, inclui 250 testes estáticos precisos. Os resultados mostram que esta função do CIEDE2000 em F# é interoperável com as outras 41 linguagens de programação.
CIEDE2000 Verification Summary :
First Verified Line : 73.2,-34,-46,97.09,38.44,-65,39.669742389892633
Duration : 51.98 s
Successes : 10000000
Errors : 0
Average Delta E : 62.9404
Average Deviation : 4.2576547981676426e-15
Maximum Deviation : 1.1368683772161603e-13Ficheiros para descarregar
Pode utilizar livremente estes ficheiros disponibilizados pelo Michel, mesmo para fins comerciais.
| Arquivo | Tamanho | Número de cliques |
|---|---|---|
| ciede-2000.fs | 4 KB | 71 |
| ciede-2000-driver.fs | 6 KB | 74 |
| ciede-2000-random.fs | 6 KB | 75 |
| test-fs.yml | 4 KB | 37 |
| reference-dataset.txt | 4 KB | 380 |
| Clique em fs.zip para baixar todos estes arquivos em um arquivo. | ||
Comunidade
O que pensa deste código fonte ou do CIEDE2000? A sua opinião é importante para nós! O livro de visitas já contém 9 mensagens - incluindo 1 em português. Dê uma vista de olhos e partilhe a sua opinião.