Skip to content

fix(colors): convert DICOM CIELab relative to the D50 white point - #598

Merged
wayfarer3130 merged 5 commits into
masterfrom
fix/cielab-d50
Oct 13, 2026
Merged

wayfarer3130 merged 5 commits into
masterfrom
fix/cielab-d50

Conversation

@fedorov

@fedorov fedorov commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

DICOM encodes CIELab values like the ICC Profile Connection Space (PS3.3 C.10.7.1.1), and the PCS reference white is D50. src/colors.js is a port of the old DCMTK IODCIELabUtil, which computes CIELab relative to D65, the sRGB white point, with no chromatic adaptation. As a result:

dcmjs agrees with itself (its round trip is exact), but it disagrees with the other toolkits. The error is larger than "slightly off a*/b*". Here is how current dcmjs displays correctly encoded (D50) colors:

Color sRGB Correct D50 DICOM Lab Current dcmjs displays
blue [0,0,255] [19378,50446,4104] [0,98,255]
lime [0,255,0] [57552,12523,53712] [72,253,26]
vein (Slicer) [0,151,206] [37989,27961,23039] [0,162,212]
CSF (Slicer) [85,188,255] [47394,28970,21928] [40,189,255]

Across the RGB cube the error averages about 13 levels per channel, up to 98. Almost all of it comes from the white point; the rest comes from the old way of handling out-of-gamut colors (shifting all channels).

Changes

This is a port of DCMTK commit 88105877:

  • sRGB → linear RGB → XYZ (D65) → linear Bradford → XYZ (D50) → CIELab, and the reverse. It uses the matrices and constants from the CSS Color Module Level 4 sample code, which are the same as DCMTK's and highdicom's.
  • xyz2RGB clips each channel to the sRGB gamut instead of subtracting the minimum from all channels. The output therefore stays in [0, 1] and the hue no longer shifts.
  • Exact CIE constants are used in labf/labfInv (ε = 216/24389, κ = 24389/27), together with the standard sRGB transfer function thresholds.
  • New helpers dicomlab2RGB8 and rgb82DICOMLAB round and clamp between 8-bit sRGB and 16-bit DICOM Lab. They mirror DCMTK's new integer overloads.
  • New d50WhitePointXYZ(). d65WhitePointXYZ() is kept, defined from the CIE x,y chromaticities.
  • New test/colors.test.js. dcmjs previously had no color tests. It uses reference values shared with DCMTK and PixelMed.

Compatibility notes

  • Same API names, corrected behaviour. No method was renamed or removed. However, rgb2XYZ, xyz2RGB, lab2XYZ and xyz2LAB now work in D50 (PCS) XYZ, as in DCMTK.
  • Existing D65-encoded data. Objects already written with rgb2DICOMLAB contain D65-encoded values. These will now display slightly differently; for example, an old-encoded pure blue decodes to [91,0,255]. Neutral and gray colors are unaffected. highdicom fix: add a missing await to an asynchronous call #469 carries the same migration note.
  • 1.0-beta branch. It has a byte-identical src/colors.js and will need the same change.

Validation

  • I checked the port against every assertion in DCMTK's new dcmiod/tests/tcielabutil.cc:
    • the white point and scalar XYZ/Lab checks
    • all 40 reference colors (within 0.03), in both directions
    • ICC white and black encoding
    • the PixelMed-consistency cases (e.g. 35732/48892/14692 → 181,82,255)
    • gamut clipping
    • 1000 random round trips
  • The 8-bit sRGB → 16-bit DICOM Lab → 8-bit sRGB round trip is exact for all 16,777,216 RGB triples. I ran the exhaustive check as a standalone script; the jest test checks a sample.
  • Tests and lint:
    • jest test/colors.test.js: 23/23 passed.
    • eslint and prettier are clean.
    • Full suite: 338/338 passed on Node 24.21.0 (the version CI uses) and on Node 24.13. After the review fixes, the full suite passes 340/340 on Node 24.20.0.
  • Second commit: a test-only backport. It fixes the Node 24 CI failures that every PR against master currently hits (Fix increment logic for stream length in AsyncDicomReader #597 too); see the comment below.

Downstream

OHIF (SEG display/export and the RTSTRUCT CIELab fallback), Slim, dicom-microscopy-viewer and the cornerstone3D adapters all use dcmjs.data.Colors. Each will need a dcmjs version bump after this is released.

🤖 Generated with Claude Code

DICOM encodes CIELab values like the ICC Profile Connection Space
(PS3.3 C.10.7.1.1), whose reference white is D50. Colors computed
CIELab relative to D65 (the sRGB white point) without chromatic
adaptation, so a*/b* were wrong for chromatic colors and dcmjs disagreed
with DCMTK, PixelMed and highdicom.

This ports DCMTK commit 88105877 (IODCIELabUtil):

- sRGB -> linear RGB -> XYZ (D65) -> Bradford -> XYZ (D50) -> CIELab and
  the reverse, using the CSS Color Module Level 4 matrices and constants
- clip out-of-gamut colors per channel instead of shifting all channels
- add dicomlab2RGB8 / rgb82DICOMLAB helpers that round and clamp
- add a test suite with the reference values shared with DCMTK/PixelMed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@netlify

netlify Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for dcmjs2 ready!

Name Link
🔨 Latest commit 67e3ddc
🔍 Latest deploy log https://app.netlify.com/projects/dcmjs2/deploys/6ace77f289fb4f3b77b4f7cc
😎 Deploy Preview https://deploy-preview-598--dcmjs2.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

Backport of the test changes from 7afe17f (#518) on 1.0-beta. Since
Node 24.21, fs.readFileSync() returns small files (e.g. sample-sr.dcm)
inside a 64 KiB pooled ArrayBuffer, so passing `buffer.buffer` to
DicomMessage.readFile() parses trailing pool memory. This broke
anonymizer.test.js and data.test.js on the Node 24 CI job for every PR
against master. Also makes test data dir creation race-free.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fedorov

fedorov commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

The test (24) failure on the first push was not caused by this change. master currently fails on Node 24, and #597 fails the same 6 tests in anonymizer.test.js and data.test.js.

Cause: Node 24.21 changed fs.readFileSync(). Small files now come back inside a 64 KiB pooled ArrayBuffer; Node 24.13 returned one of exactly the file's size. test/sample-sr.dcm is 4,456 bytes, so fs.readFileSync(...).buffer hands DicomMessage.readFile() the whole 64 KiB pool, and the parser reads past the end of the file.

Fix: a262ec3 backports the test-only changes from 7afe17f (#518), which already fixed this on 1.0-beta. It adds readFileAsArrayBuffer() in testUtils.js and uses it everywhere. It applied cleanly. I left out the 1.0 pipeline-smoke test. With this commit the suite passes 338/338 on Node 24.21.0 and 24.13.

If you'd rather land the test fix on its own, I can split it into a separate PR.

@wayfarer3130 wayfarer3130 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thank you for this port. I reviewed the color math against the standards, and the math is correct:

  • The DICOM encoding agrees with PS3.3 C.10.7.1.1 and the ICC v4 16-bit Lab encoding. sRGB white encodes to [65535, 32896, 32896], and black encodes to [0, 32896, 32896].
  • The sRGB matrices and the Bradford matrices are the same as the CSS Color 4 sample code, coefficient for coefficient.
  • The transfer function agrees with IEC 61966-2-1. labf and labfInv use the exact CIE values of ε and κ.
  • I ran the reference values from the description, and I got the same results: blue [19378,50446,4104], lime [57552,12523,53712], and 35732/48892/14692 to 181,82,255. jest test/colors.test.js passes (22/22).

I found one bug in a new helper, and some smaller items. See the inline comments. Other items are on lines that the diff does not change:

  1. D50 white point. The code calculates D50 from the x,y chromaticities: [0.96430, 1, 0.82510]. The PCS illuminant in ICC.1 is [0.9642, 1, 0.8249]. I measured the difference: it is 4.3 DICOM units at most (about 0.016 in a*/b*), at white. The choice of this PR agrees with DCMTK, highdicom, and CSS, and sRGB white encodes to exactly 0x8080. With the ICC values, sRGB white encodes to 32900/32892. Thus I think that the choice is correct. A short comment that tells the reader that the choice is intentional can prevent a later "fix" to the ICC values.
  2. VTKjs adapter. src/adapters/VTKjs/Segmentation.js lines 4-11 still contain a local dicomlab2RGBA that uses Math.round(x * 255). A TODO there asks to move the function into Colors. The new Colors.dicomlab2RGB8 does this job, with rounding and clamping. I suggest that the adapter uses dicomlab2RGB8, so that the repository has one 8-bit conversion.
  3. test/data.test.js. The new readFileAsArrayBuffer helper does not replace the three inline copies of the same byteOffset/byteLength slice (near lines 797, 933, and 959). Also, line 1819 makes a copy that is not necessary: new Uint8Array(file).buffer. file is already a standalone ArrayBuffer.
  4. Scope of the PR. This PR contains a change that users can see: existing SEG objects with D65-encoded colors will display differently. DICOM requires D50, so this change is a correction of the old behaviour, and the change is correct. The description tells this clearly, and I thank you for that. The second commit is a CI fix for Node 24 in 11 test files, and the CI fix is not related to colors. I suggest a separate PR for the CI fix. Then maintainers can merge the CI fix (which #597 also needs) without a decision about the color change.

Comment thread src/colors.js Outdated

// 8 bit sRGB -> 16 bit DICOM CIELab, rounded and clamped
static rgb82DICOMLAB(rgb) {
return Colors.rgb2DICOMLAB(rgb.map(n => n / 255.0)).map(n =>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bug: when rgb is a Uint8Array or a Uint8ClampedArray, rgb.map(...) returns an array of the same type. Thus each value n / 255.0 becomes 0 or 1 (the fraction is truncated) before the conversion.

I got these results:

Colors.rgb82DICOMLAB(Uint8Array.of(128, 64, 32)) // [0, 32896, 32896] (black)
Colors.rgb82DICOMLAB([128, 64, 32])              // [23025, 39675, 41113]

Segment colors and LUT data often come in a Uint8Array. A possible fix:

Suggested change
return Colors.rgb2DICOMLAB(rgb.map(n => n / 255.0)).map(n =>
return Colors.rgb2DICOMLAB(Array.from(rgb, n => n / 255.0)).map(n =>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in d80e16b. rgb82DICOMLAB now uses Array.from(rgb, n => n / 255.0). A new test checks that Uint8Array.of(128, 64, 32) gives the same result as [128, 64, 32].

Comment thread src/colors.js Outdated
return Math.min(1.0, Math.max(0.0, n));
}

static roundClamp(n, max) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

roundClamp does not stop NaN: NaN < 0.0 and NaN > max are both false, and Math.floor(NaN + 0.5) is NaN. For example, Colors.dicomlab2RGB8([1, 2]) returns [NaN, NaN, NaN]. The input is not valid, so the severity is low. But the doc comment says "rounded and clamped", and a caller can write NaN into a LUT or a US element. A Number.isNaN check (return 0, or throw an error) agrees with the doc comment.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in d80e16b. roundClamp now returns 0 when the value is NaN. Thus Colors.dicomlab2RGB8([1, 2]) now returns [0, 0, 0]. A new test checks this result.

Comment thread src/colors.js Outdated
}
}

static clamp01(n) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

clamp01 and roundClamp are internal helpers, but as static methods of the exported Colors class they become public API. Downstream code (OHIF, Slim, the cornerstone3D adapters) can start to use them, and then a later change to them is a breaking change. I suggest module-level functions, the same as D50_WHITEPOINT_XYZ and D65_WHITEPOINT_XYZ.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in d80e16b. clamp01 and roundClamp are now module-level functions, and the Colors class does not export them.

Comment thread src/colors.js
// white points of D65 light point (CIELAB standard white point)
return [0.950456, 1.0, 1.088754];
// white point of D65 illuminant (native white point of sRGB)
return [...D65_WHITEPOINT_XYZ];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

DICOM defines CIELab relative to D50 (PS3.3 C.10.7.1.1, through the ICC PCS). Thus the change from D65 to D50 corrects an error in the old code, and the change is the intended behaviour. I suggest that the PR documents the change as a correction, in the code and in the changelog, and not only in the PR description:

  • The doc comments of rgb2XYZ, xyz2RGB, lab2XYZ, and xyz2LAB tell the reader that the XYZ values are relative to D50, because DICOM requires D50.
  • The changelog entry tells the reader that the old D65 results were wrong, and that values that the old rgb2DICOMLAB wrote will now display slightly differently. The PR description already gives an example: an old pure blue now decodes to [91,0,255].
  • The compatibility notes now use the heading "Public API unchanged". I suggest a heading such as "Same API names, corrected behaviour", so that a downstream maintainer does not read the change as a no-op.

After this PR, no code in dcmjs calls d65WhitePointXYZ(), and its Z value changes from 1.088754 to 1.08906. A caller that divides the output of rgb2XYZ by d65WhitePointXYZ() now mixes D50 XYZ with a D65 white. A short note here can tell the user to use d50WhitePointXYZ() with the XYZ functions, and to use d65WhitePointXYZ() only for D65-relative sRGB work.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in d80e16b:

  • rgb2XYZ, xyz2RGB, lab2XYZ, and xyz2LAB now each have a comment that says that the XYZ values are relative to D50.
  • d65WhitePointXYZ() now has a doc comment. The comment tells the reader not to use the D65 white with the XYZ values of this class, and to use d50WhitePointXYZ().
  • A comment at D50_WHITEPOINT_XYZ tells the reader that the x,y chromaticity values are intentional and that they are not the ICC.1 values.
  • changelog.md has a new entry. The entry says that the old D65 results were wrong, and that old encoded colors now display slightly differently (old pure blue decodes to [91, 0, 255]).

Comment thread test/colors.test.js Outdated
expect(Colors.dicomlab2RGB8([19378, 50557, 3680])).toEqual([0, 0, 255]);
});

it("clips colors outside the sRGB gamut to the valid range", () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This test only checks that each output value is in [0, 1]. The old approach (subtract the minimum from all channels), followed by a clamp, also passes this test. Thus the test does not show that clipping per channel keeps the hue, and the description claims that it does. I suggest assertions on specific clipped outputs, for example the expected values of the gamut-clipping test in DCMTK tcielabutil.cc.

@wayfarer3130 wayfarer3130 Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in d80e16b and 67e3ddc. The test now checks the exact 8-bit output of the four corner values, for example [65535, 65535, 65535] gives [255, 67, 0]. The test also checks that lab2RGB([50, 127, -128]) gives R = 0.838545, G = 0, and B = 1.

I compared the expected values with the old approach (subtract the minimum from all channels, then clamp to 1). The old approach gives different results for three of the four corners and for the Lab value. For example, [65535, 65535, 65535] gives [255, 86, 0], and [50, 127, -128] gives [231, 0, 255]. Thus the test fails on the old approach.

@pieper

pieper commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

Historical note: the original dcmjs color conversion code was just a direct translation of the DCMTK code, so bringing it in line with the corrections from there makes sense (as linked from the Changes section above).

@fedorov

fedorov commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

@wayfarer3130 I must admit I do not have the expertise in this topic - the PR is generated by Claude, as declared in the opener. I just wanted this bug to be fixed around the same time in all implementations. If you like, I can ask my Claude to read the comments you (or your Claude) made, and update the code, but you might as well do it directly with your Claude - the latter might be more efficient. Please let me know what you would prefer.

wayfarer3130 and others added 3 commits October 13, 2026 14:26
- rgb82DICOMLAB: use Array.from so typed array input is not truncated
- roundClamp returns 0 for NaN; clamp01/roundClamp are module functions,
  not public static methods
- document that the XYZ functions are D50-relative, that d65WhitePointXYZ
  must not be mixed with them, and why D50 uses the x,y chromaticities
- assert exact per-channel gamut clipping results in the tests
- VTKjs adapter uses Colors.dicomlab2RGB8
- changelog entry for the corrected behaviour

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@wayfarer3130

Copy link
Copy Markdown
Contributor

@fedorov Thank you. I made the changes from my review, and I pushed the changes to this branch:

  • d80e16b fixes the five inline comments. See the replies on each comment.
  • d80e16b also fixes the items of the review summary that are not on changed lines:
    1. D50 white point. A comment at D50_WHITEPOINT_XYZ now says that the x,y chromaticity values are intentional, and why.
    2. VTKjs adapter. src/adapters/VTKjs/Segmentation.js now uses Colors.dicomlab2RGB8. I removed the TODO.
    3. Changelog. changelog.md has an entry that describes the D50 change as a correction.
  • 2ee37b7 replaces the three inline buffer slices in test/data.test.js with readFileAsArrayBuffer. The commit also removes the unnecessary copy new Uint8Array(file).buffer.
  • 67e3ddc corrects a comment in the gamut clipping test.
  • I changed the heading "Public API unchanged" in the description to "Same API names, corrected behaviour".

I kept the Node 24 CI fix (a262ec3) in this PR. A split needs a force push to this branch. If a maintainer prefers a separate PR for the CI fix, I can do the split.

Tests: jest passes 340/340 on Node 24.20.0, and eslint is clean.

🤖 Generated with Claude Code

@wayfarer3130
wayfarer3130 merged commit 3843de7 into master Oct 13, 2026
20 checks passed
@wayfarer3130
wayfarer3130 deleted the fix/cielab-d50 branch October 13, 2026 21:54
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 0.52.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

wayfarer3130 added a commit that referenced this pull request Nov 24, 2026
Merge from 0.x
* fix(colors): convert DICOM CIELab relative to the D50 white point

1.0 port of #598 (commit 3843de7).

src/colors.js and src/adapters/VTKjs/Segmentation.js on 1.0-beta were
the same as on master before #598, so this takes the #598 versions of
both files: sRGB -> XYZ (D65) -> Bradford -> XYZ (D50) -> CIELab and
the reverse, per channel gamut clipping, and the new dicomlab2RGB8,
rgb82DICOMLAB and d50WhitePointXYZ. The VTKjs adapter uses
dicomlab2RGB8. The changelog entry is the same as on master.

The 0.x test test/colors.test.js moves to
test/issues/pr598-colors-d50.test.js. The test file changes of #598
for readFileAsArrayBuffer were a backport from 1.0-beta and are not
needed here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: record the D50 CIELab conversion in the beta 1 release notes

Maintainer decision Q1 of the review of the 1.0 port of #598. The changelog.md entry stays as it is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(bundle-size): raise the ceilings to 1.083 and 1.065 for the D50 CIELab conversion

On the current 1.0-beta, the #598 colors code takes dcmjs.js to x1.0825 and dcmjs.es.js to x1.0649.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants