Skip to content

Fix dist_cie2000/dist_cie94 to implement the published CIE formulas - #425

Merged
jquast merged 7 commits into
jquast:masterfrom
rahul05ranjan:bugfix/cie-distance-formulas
Nov 20, 2026
Merged

jquast merged 7 commits into
jquast:masterfrom
rahul05ranjan:bugfix/cie-distance-formulas

Conversation

@rahul05ranjan

Copy link
Copy Markdown

Proposed change

dist_cie2000 and dist_cie94 did not implement the published CIE formulas; this PR ports both to the canonical formulation published in Sharma, Wu & Dalal (2005), "The CIEDE2000 Color-Difference Formula: Implementation Notes, Supplementary Test Data, and Mathematical Observations".

Closes #424 (and supersedes the unfixed symptom reported in #321).

dist_cie2000 root causes fixed

  1. radians/degrees mixing: atan2() returns radians, but hue values were wrapped with % 360, compared against 180/360 degree thresholds (making the hue-mean special cases unreachable dead code, since |radians| <= pi < 180), and fed to cos()/sin() alongside degree constants (30, 2h, 3h+6, 4h-63, dh/2, 60*exp(...), 275, 25). Hue angles are now converted to degrees and the constants converted to radians.
  2. rotation term: r_t was computed from delta_h (the ΔH magnitude) where CIEDE2000 ties it to the mean hue angle h̄' — this also restores the symmetry reported in dist_cie2000 is not symmetric for swapped RGB arguments #321 (dist_cie2000(a, b) == dist_cie2000(b, a)).
  3. chroma mean: s_c/s_h/r_t now use the post-G chroma mean C̄' as the published formula requires (previously the pre-G c_mean).

dist_cie94 root cause fixed

The hue difference in quadrature must be dH² = Δa² + Δb² − ΔC² (chroma–hue decomposition; non-negative by Cauchy–Schwarz). The old code computed Δa² + Δb² + ΔC², inventing a hue difference for colors that differ only in chroma — e.g. Lab (50, 60, 0) vs (50, 30, 0) must be ΔE₉₄ = 30/(1+0.045·60) ≈ 8.108 with a zero hue term. A max(0.0, …) guard clamps float rounding artifacts of the subtraction.

Both public functions keep their signatures and "square of the distance" return semantics; the Lab math now lives in _cie94_lab/_cie2000_lab so it can be verified against published Lab test vectors directly.

Verification

  • Published test data: _cie2000_lab reproduces pairs 1–3 of the Sharma et al. (2005) supplementary test data exactly — sqrt(_cie2000_lab(lab1, lab2)) returns 2.0425 / 2.8615 / 3.4412 (before the fix: 1.1946 / 1.6995 / 2.2303).
  • Symmetry: the dist_cie2000 is not symmetric for swapped RGB arguments #321 repro pair (73, 253, 26) vs (110, 13, 181) now returns identical distances either way.
  • CIE94: the collinear-chroma case is analytic (30/(1+0.045·60)), and a general Lab pair is pinned against the published closed form.
  • No behavior change for the other algorithms; full test suite passes locally: 1834 passed, 179 skipped (5 new tests added).

Type of change

  • Bugfix (non-breaking change which fixes an issue)

Checklist

  • Tests added for the new behavior (published-vector, symmetry, and analytic cases)
  • All new and existing tests pass locally
  • Changelog entry added to docs/history.rst (1.52 unreleased section)

@codecov

codecov Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 97.76%. Comparing base (663e867) to head (a30fa6b).

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #425   +/-   ##
=======================================
  Coverage   97.76%   97.76%           
=======================================
  Files          13       13           
  Lines        4118     4118           
  Branches      697      699    +2     
=======================================
  Hits         4026     4026           
  Misses         70       70           
  Partials       22       22           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@codspeed

codspeed Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing rahul05ranjan:bugfix/cie-distance-formulas (a30fa6b) with master (663e867)

Open in CodSpeed

@avylove

avylove commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

It seems like you have a better understanding of the color algorithms than we do, but two things.

  • Can you link to the published data you referenced?
  • What is the reason behind the double function calls?

@rahul05ranjan

Copy link
Copy Markdown
Author

Hi avylove, thanks for taking a look — happy to back both points up.

The published data. The formulation and the test vectors both come from Sharma, Wu & Dalal (2005), "The CIEDE2000 Color-Difference Formula: Implementation Notes, Supplementary Test Data, and Mathematical Observations", Color Research & Application 30(1), 21–30:

test_dist_cie2000_matches_published_vectors checks pairs 1–3 of the supplementary test data in that paper (ΔE = 2.0425 / 2.8615 / 3.4412) directly against _cie2000_lab, and _cie94_lab is pinned against the CIE94 closed form for the same reason.

The double function calls. If you mean the two G-shaped sqrt(c**7 / (c**7 + 25**7)) expressions inside _cie2000_lab — that's deliberate, and it's one of the things the old code got wrong. In the published formula the G transform for a' is computed from the pre-G mean chroma C̄, while the R_T rotation term uses the post-G mean chroma C̄' — so the same expression appears twice over different chroma means, and it isn't a redundant re-computation. (Sharma et al.'s implementation notes flag exactly this pair.) The pre-fix code used the pre-G c_mean in r_t and in s_c/s_h, which is the third bullet in the PR description. If it reads clearer, I'm happy to factor it into a tiny _G(c) helper so the two call sites and their different arguments stand out — just say the word and I'll push that as a follow-up commit.

(If you instead meant the rgb_to_lab(*rgb1), rgb_to_lab(*rgb2) pair in the wrappers — that's just the one conversion per input color, kept out of the Lab math so the published Lab vectors can be tested without a round-trip through rgb_to_lab obscuring exact agreement.)

@avylove

avylove commented Oct 30, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the response and the PR. I actually meant the wrappers. They don't seem to add anything except additional function calls. In that same vein, there's some optimization that can be done. A few things stand out:

  • Multiplying by values that are assigned to 1
  • using x ** 2 is usually more expensive than x * x
  • using x / 2 is usually more expensive than x * 0.5
  • Some calculations are done twice, like (l_mean - 50) ** 2), assignment and/or reducing this might be more efficient
  • Assignments that are used only once

I feel it's better to make the code as efficient as you can and then explain it in comments. Removing the extra function call and optimizing the math, might make the code 20 - 50% faster.

I would also put the reference links in the comments

And fix the linting and docformatter failures

But from what I can tell, this does seem to fix the symmetric distance issue and the color tables aren't drastically different.

CIE94 - Before
cie94_before

CIE94 - After
cie94_after

CIE2000 - Before
cie2000_before

CIE2000 - After
cie2000_afer

@rahul05ranjan

Copy link
Copy Markdown
Author

Hi @avylove — thanks, all applied in 4a345d8, and your estimate was on target: CIE94 measures ~48% and CIEDE2000 ~26% faster on my benchmark, with bit-identical outputs on every pair I checked.

The wrappers are gone. _cie94_lab and _cie2000_lab are removed — dist_cie94 and dist_cie2000 now run the full math directly, with one rgb_to_lab call per argument. The published-vector tests keep validating the CIEDE2000 math by feeding the Sharma/Wu/Dalal pairs through the public function with rgb_to_lab patched to the identity, and a new test asserts each RGB argument is converted exactly once.

Math optimizations, as you listed: dropped the multiplications by the factors assigned to 1 (k_L/k_C/k_H and S_L in CIE94), replaced x ** 2 with x * x and / 2 with * 0.5, the repeated (l_mean - 50) ** 2, c_mean ** 7 and c_meanp ** 7 are now computed once, and single-use temporaries are inlined.

References in comments: the CIE94 section link and the Sharma/Wu/Dalal (2005) paper (with its implementation-notes URL) now sit in the comments next to the math they document.

Linting and docformatter: the isort failure was the import order (the length-sorted style) and the docformatter failure was in the removed helper docstrings — both fixed. flake8, isort, docformatter, mypy, pylint, pydocstyle and codespell all pass locally with the CI-pinned tools. The new revision's Actions run needs a maintainer approval to start (fork PR), so it will go green as soon as someone approves the workflow.

@avylove avylove left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this looks great! I added a couple more places it could be optimized and you'll also want to look at where you have integers that are operating against floats. Really all the numbers in the code should be floats, so 2.0 instead of 2. This lets the PEP 659 improvements introduced in Python 3.11 work a little better.

Comment thread blessed/color.py Outdated
# G = 0.5 * (1 - sqrt(c_mean**7 / (c_mean**7 + 25**7)))
c_1 = sqrt(a_1 * a_1 + b_1 * b_1)
c_2 = sqrt(a_2 * a_2 + b_2 * b_2)
c_7 = ((c_1 + c_2) * 0.5) ** 7

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be collapsed into
c_7 = ((sqrt(a_1 * a_1 + b_1 * b_1) + sqrt(a_2 * a_2 + b_2 * b_2)) * 0.5) ** 7.0

Comment thread blessed/color.py Outdated
Comment on lines +239 to +240
r_t = (-2 * sqrt(c_7p / (c_7p + 25 ** 7)) *
sin(radians(60 * exp(-(((h_mean - 275) / 25) ** 2)))))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
r_t = (-2 * sqrt(c_7p / (c_7p + 25 ** 7)) *
sin(radians(60 * exp(-(((h_mean - 275) / 25) ** 2)))))
d_theta = (h_mean - 275.0) * 0.04
r_t = (-2.0 * sqrt(c_7p / (c_7p + 25.0 ** 7.0)) * sin(radians(60.0 * exp(-(d_theta * d_theta)))))

@rahul05ranjan

Copy link
Copy Markdown
Author

Thanks @avylove — really glad the formulation checks out! Happy to apply the float-literal pass (2 → 2.0) and the inline suggestions in a small additive commit if you'd like them included in this PR; otherwise they can land in a follow-up and this is ready from my side whenever you are.

@avylove

avylove commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

@rahul05ranjan I think it needs another commit. There's also still a linting failure. You can ignore the CodSpeed issue. that looks like a config problem.

@rahul05ranjan

Copy link
Copy Markdown
Author

Done — 255a7fc pushes the offered float-literal pass (1 → 1.0, 2 → 2.0, 25 → 25.0, and the angle constants) plus the single-use chroma temporaries in dist_cie2000 inlined.

The linting failures were pylint on the new tests: the symmetric-distance assert read as arguments-out-of-order (W1114 — now split into named distance_forward/distance_reverse) and the CIE94 reference test was over the too-many-locals budget (R0914 — unpackings folded away). pylint blessed and pylint_tests with the CI disables both rate 10.00/10 locally, and all 41 color tests pass. CodSpeed left alone per your note.

@rahul05ranjan

Copy link
Copy Markdown
Author

Following up on the linting note: pylint_tests was still red on 255a7fc — W1114 (arguments-out-of-order) firing on the deliberately swapped call in test_dist_cie2000_is_symmetric (the named-locals split didn't help since the check keys on the call arguments themselves). 713c2ec marks that one line with an inline pylint: disable=arguments-out-of-order plus a comment noting the swap is intentional; pylint --disable invalid-name --disable import-outside-toplevel --disable protected-access --disable use-implicit-booleaness-not-comparison-to-string --disable unused-argument tests rates 10.00/10 locally now. The Run benchmarks job failure is the CodSpeed CLI installer error ("Unsupported system"), left alone per your note.

@avylove

avylove commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator

There are still a couple unresolved comments and the pylint issue is better fixed by renaming the arguments. If you used rgb-a and rgb-b as the argument names it would probably get rid of the warning without having to disable it. It's only firing because the variable names are the same as the argument names.

@rahul05ranjan

Copy link
Copy Markdown
Author

Thanks @avylove — all applied in 28f1ea6:

  • Unresolved comments: collapsed the c_1/c_2 chroma temporaries into the single c_7 expression, and introduced d_theta = (h_mean - 275.0) * 0.04 for the R_T hue term as suggested (outputs are bit-identical; all 41 color tests pass, including the Sharma test vectors).
  • W1114: renamed dist_cie2000's parameters to rgb_a/rgb_b, so the symmetry test's rgb1/rgb2 loop variables no longer collide with the argument names — the inline disable in the test is gone, and pylint rates both blessed and tests 10.00/10 with the CI commands.

Also updated the :arg: docstring entries to match the new parameter names. Happy to fold anything further in if you spot it — otherwise this should be ready for another look whenever you have a moment.

@avylove

avylove commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator

I suggested renaming the arguments, not the parameters. Now the parameters don't match the other functions.

@rahul05ranjan

Copy link
Copy Markdown
Author

Understood, thanks for the correction — fixed in 9580e84: dist_cie2000 is back on rgb1/rgb2 parameters matching the other dist_* functions, and the swapped arguments in test_dist_cie2000_is_symmetric are now named rgb_a/rgb_b instead, which is what silences the W1114 warning (no inline disable). pylint blessed and the tests pylint both rate 10.00/10, and all 41 color tests pass.

@avylove avylove left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the updates and sorry for the delay. Code looks good to me, but noticed a few things in the tests. Would also be good to rebase against master so codspeed runs properly.

Comment thread tests/test_color.py Resolved
Comment thread tests/test_color.py Resolved
Comment thread tests/test_color.py Resolved
rahul05ranjan and others added 7 commits November 14, 2026 15:20
dist_cie2000 mixed radians from atan2 with degree constants (the hue-mean
special cases were unreachable dead code), tied the rotation term to the
hue difference instead of the mean hue angle (the symmetry symptom of
hue term in quadrature as da**2 + db**2 + dC**2 instead of
da**2 + db**2 - dC**2, inventing a hue difference for colors that only
differ in chroma.

Both functions now follow the formulation published by Sharma, Wu &
Dalal (2005) (hue arithmetic in degrees; CIE94 graphic-arts factors
unchanged), and are verified against the published supplementary test
data (Table 1): pairs 1-3 reproduce 2.0425 / 2.8615 / 3.4412 exactly,
dist_cie2000 is symmetric again, and the CIE94 hue term is zero for
collinear-chroma Lab pairs.

Fixes jquast#424

Co-authored-by: rahul05ranjan <[email protected]>
Remove the _cie94_lab/_cie2000_lab wrappers (dist_cie94/dist_cie2000
now run the full math directly, one rgb_to_lab call per argument),
drop the multiplications by the k factors assigned to 1, use x * x
and * 0.5 instead of x ** 2 and / 2, compute the repeated
(l_mean - 50) ** 2, c_mean ** 7 and c_meanp ** 7 once, inline
single-use temporaries, and put the reference links (CIE94 wiki,
Sharma/Wu/Dalal 2005) in comments. Tests now feed the published
Lab vectors through dist_cie2000 with rgb_to_lab patched to the
identity, and assert each RGB argument is converted exactly once.
Measured on 3 RGB pairs: CIE94 ~48% faster, CIEDE2000 ~26% faster;
outputs are bit-identical on the pairs tested.

Also fixes the isort import order and docformatter CI failures.
Per review: float literals throughout the CIE94/CIE2000 math
(1 -> 1.0, 2 -> 2.0, 25 -> 25.0, 180/360 -> 180.0/360.0), and
inline the single-use chroma temporaries c_1/c_2 in dist_cie2000.

tests: restructure the symmetric-distance assertion so pylint
no longer reads it as arguments-out-of-order (W1114), and drop
the intermediate unpackings in the CIE94 reference test to come
under the too-many-locals budget (R0914). All 41 color tests
pass; pylint blessed and pylint_tests (CI disables) at 10.00/10.

Co-authored-by: rahul05ranjan <[email protected]>
Per review: collapse the c_1/c_2 chroma temporaries into a single
c_7 expression and introduce d_theta for the R_T hue term (25.0 ** 7.0).

Rename dist_cie2000's rgb1/rgb2 parameters to rgb_a/rgb_b so pylint
no longer matches the symmetry test's loop variables to the parameter
names (W1114) and the inline disable in the test can be dropped.

pylint 10.00/10 on both blessed and tests; all 41 color tests pass.
…ename the swapped arguments in the symmetry test instead
Expand the published CIEDE2000 test vectors from the first three
pairs to all 34 pairs of the supplementary test data of Sharma, Wu
& Dalal (2005), and add the source link for the dataset
(https://hajim.rochester.edu/ece/sites/gsharma/ciede2000/).

Replace the converter call-count test with its behavioral contract:
an RGB pair must yield the same distance as its pre-converted Lab
pair, so both arguments flow through rgb_to_lab without counting
calls or depending on lru_cache.

Drop test_dist_cie94_matches_reference_for_general_pair: it
re-implemented the CIE94 formula to check the formula, and no
freely published CIE94 test vectors exist to test against instead.
The collinear-chroma property test keeps covering the hue-term fix.

Co-authored-by: rahul05ranjan <[email protected]>
@rahul05ranjan
rahul05ranjan force-pushed the bugfix/cie-distance-formulas branch from 9580e84 to a30fa6b Compare November 14, 2026 15:21
@rahul05ranjan

Copy link
Copy Markdown
Author

Thanks for the review! All three test points are addressed in a30fa6b, and the branch is now rebased onto master as requested.

  • CIE94 general-pair test: You're right that it just re-implemented the formula it was testing, so I removed it. I couldn't find freely published CIE94 test vectors to test against instead (the formula's originating report, CIE 116-1995, isn't public), so rather than keep a circular test I dropped it; the collinear-chroma property test still covers the hue-term fix. For CIEDE2000 I expanded the published-vector test from the first 3 pairs to the complete 34-pair supplementary test data of Sharma, Wu & Dalal (2005) — all pairs reproduce the published values within the 4-decimal rounding of the source.

  • test_dist_cie2000_converts_each_rgb_argument_once: Fair question — it was a call-count test added during the optimization pass. I replaced it with the underlying behavioral contract: dist_cie2000 on an RGB pair must return the same distance as dist_cie2000 on the pair's pre-converted Lab values, so it now verifies both arguments flow through rgb_to_lab without counting calls or depending on the cache.

  • Source link: Added next to the citation — the test data is published at https://hajim.rochester.edu/ece/sites/gsharma/ciede2000/ (the www2.ece.rochester.edu URL referenced in color.py has moved there, too).

The rebase onto master was clean apart from a changelog conflict in docs/history.rst, resolved by keeping both master's and this PR's entries. Since that rewrote history, the update was pushed with --force-with-lease.

Tests on the rebased head (a30fa6b): tests/test_color.py — 40 passed; full suite — 1859 passed, 179 skipped.

@avylove

avylove commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator

@jquast This looks ok to me. It has an AI smell to it, but all my nits were addressed. I didn't dig into the math, but if the results are close to what we had before and it solves the symmetric issue, then it seems like it should be fine.

@jquast

jquast commented Nov 14, 2026

Copy link
Copy Markdown
Owner

Yeah I saw your screenshots from before, they look slightly different, I don't understand the hard math but it can't hurt, this is our 4th AI-generated "your CIE is wrong" and the only way to prevent a 5th is by merging it. Or at least you'd hope :)

I get so many AI generated in wcwidth that I maintain a section of "Unlikely Sequences" in documentation about it, my stance is that if "correcting" something that is imperceptibly different prevents additional AI agents from "boiling water" over making the same PR's multiple times, then it is good to merge such changes.

@jquast
jquast merged commit f920374 into jquast:master Nov 20, 2026
15 of 16 checks passed
@rahul05ranjan

Copy link
Copy Markdown
Author

Appreciate the merge on #425 — nice to see "Fix dist_cie2000/dist_cie94 to implement the published CIE formulas" ship.

On a personal note: I'm on the lookout for my next role (Full Stack (PHP, NodeJs, Python) / Data Science / Applied AI / Devtools, based in India). Happy to chat if there's an opening on your side or one you'd recommend:
LinkedIn: https://www.linkedin.com/in/rahulswt7/ · GitHub: https://github.com/rahul05ranjan

jquast added a commit that referenced this pull request Nov 20, 2026
* change uncicode arrows -> ascii arrows
* reduce monster-sized changelog item from #425
@jquast

jquast commented Nov 20, 2026

Copy link
Copy Markdown
Owner

Don't listen to him! I have over 20 years experience in over 30 languages and 15 years of cloud, based in USA! Hire me first !!

@rahul05ranjan

Copy link
Copy Markdown
Author

Ha — you win that exchange, Jeff! Over 20 years in 30 languages is a résumé I can't outbid, so I'll just take the consolation prize: the CIE formulas landed in the right repo with the right maintainer. 🙂

All jokes aside, thanks for the careful review on this one — good to see the corrected color distances ship.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

dist_cie2000 and dist_cie94 do not implement the published CIEDE2000/CIE94 formulas

3 participants