Repository navigation
fix(colors): convert DICOM CIELab relative to the D50 white point - #598
Conversation
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]>
✅ Deploy Preview for dcmjs2 ready!
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]>
|
The Cause: Node 24.21 changed Fix: a262ec3 backports the test-only changes from 7afe17f (#518), which already fixed this on If you'd rather land the test fix on its own, I can split it into a separate PR. |
wayfarer3130
left a comment
There was a problem hiding this comment.
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.
labfandlabfInvuse 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], and35732/48892/14692to181,82,255.jest test/colors.test.jspasses (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:
- 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 to32900/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. - VTKjs adapter.
src/adapters/VTKjs/Segmentation.jslines 4-11 still contain a localdicomlab2RGBAthat usesMath.round(x * 255). A TODO there asks to move the function intoColors. The newColors.dicomlab2RGB8does this job, with rounding and clamping. I suggest that the adapter usesdicomlab2RGB8, so that the repository has one 8-bit conversion. test/data.test.js. The newreadFileAsArrayBufferhelper does not replace the three inline copies of the samebyteOffset/byteLengthslice (near lines 797, 933, and 959). Also, line 1819 makes a copy that is not necessary:new Uint8Array(file).buffer.fileis already a standaloneArrayBuffer.- 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.
|
|
||
| // 8 bit sRGB -> 16 bit DICOM CIELab, rounded and clamped | ||
| static rgb82DICOMLAB(rgb) { | ||
| return Colors.rgb2DICOMLAB(rgb.map(n => n / 255.0)).map(n => |
There was a problem hiding this comment.
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:
| return Colors.rgb2DICOMLAB(rgb.map(n => n / 255.0)).map(n => | |
| return Colors.rgb2DICOMLAB(Array.from(rgb, n => n / 255.0)).map(n => |
There was a problem hiding this comment.
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].
| return Math.min(1.0, Math.max(0.0, n)); | ||
| } | ||
|
|
||
| static roundClamp(n, max) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| } | ||
| } | ||
|
|
||
| static clamp01(n) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Fixed in d80e16b. clamp01 and roundClamp are now module-level functions, and the Colors class does not export them.
| // 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]; |
There was a problem hiding this comment.
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, andxyz2LABtell 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
rgb2DICOMLABwrote 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.
There was a problem hiding this comment.
Fixed in d80e16b:
rgb2XYZ,xyz2RGB,lab2XYZ, andxyz2LABnow 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 used50WhitePointXYZ().- A comment at
D50_WHITEPOINT_XYZtells the reader that the x,y chromaticity values are intentional and that they are not the ICC.1 values. changelog.mdhas 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]).
| expect(Colors.dicomlab2RGB8([19378, 50557, 3680])).toEqual([0, 0, 255]); | ||
| }); | ||
|
|
||
| it("clips colors outside the sRGB gamut to the valid range", () => { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
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). |
|
@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. |
- 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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@fedorov Thank you. I made the changes from my review, and I pushed the changes to this branch:
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: 🤖 Generated with Claude Code |
|
🎉 This PR is included in version 0.52.1 🎉 The release is available on: Your semantic-release bot 📦🚀 |
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]>
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.jsis a port of the old DCMTKIODCIELabUtil, which computes CIELab relative to D65, the sRGB white point, with no chromatic adaptation. As a result:dicomlab2RGBshows the wrong colors forRecommendedDisplayCIELabValuewritten by DCMTK/dcmqi, PixelMed or highdicom. Those tools are all moving to D50 (DCMTK 88105877, highdicom fix: add a missing await to an asynchronous call #469, dcmqi docs: rename INTENTIONAL_CHANGES to BREAKING_CHANGES, drop review jargon #563).rgb2DICOMLABwrites D65-relative values into new objects. OHIF's SEG export uses it.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:
[0,0,255][19378,50446,4104][0,98,255][0,255,0][57552,12523,53712][72,253,26][0,151,206][37989,27961,23039][0,162,212][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:
xyz2RGBclips 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.labf/labfInv(ε = 216/24389, κ = 24389/27), together with the standard sRGB transfer function thresholds.dicomlab2RGB8andrgb82DICOMLABround and clamp between 8-bit sRGB and 16-bit DICOM Lab. They mirror DCMTK's new integer overloads.d50WhitePointXYZ().d65WhitePointXYZ()is kept, defined from the CIE x,y chromaticities.test/colors.test.js. dcmjs previously had no color tests. It uses reference values shared with DCMTK and PixelMed.Compatibility notes
rgb2XYZ,xyz2RGB,lab2XYZandxyz2LABnow work in D50 (PCS) XYZ, as in DCMTK.rgb2DICOMLABcontain 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-betabranch. It has a byte-identicalsrc/colors.jsand will need the same change.Validation
dcmiod/tests/tcielabutil.cc:35732/48892/14692 → 181,82,255)jest test/colors.test.js: 23/23 passed.mastercurrently 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