Skip to content

Color conversion with ICC profiles #1567

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 108 commits into
base: main
Choose a base branch
from
Draft

Conversation

JimBobSquarePants
Copy link
Member

@JimBobSquarePants JimBobSquarePants commented Feb 27, 2021

Prerequisites

  • I have written a descriptive pull-request title
  • I have verified that there are no overlapping pull-requests open
  • I have verified that I am following matches the existing coding patterns and practice as demonstrated in the repository. These follow strict Stylecop rules 👮.
  • I have provided test coverage for my change (where applicable)

Description

Note: This is a replacement for the original PR #273 from @JBildstein that was automatically closed by our Git LFS history rewrite. Individual commits have unfortunately been lost in the process. Help is very much needed to complete the work.

As the title says, this adds methods for converting colors with an ICC profile.

Architecturally, the idea is that the profile is checked once for available and appropriate conversion methods and a then a delegate is stored that only takes the color values to convert and returns the calculated values. The possible performance penalty for using a delegate is far smaller than searching through the profile for every conversion. I'm open for other suggestions though.

There are classes to convert from the profile connection space (=PCS, can be XYZ or Lab) to the data space (RGB, CMYK, etc.) and vice versa. There are also classes to convert from PCS to PCS and Data to Data but they are only used for special profiles and are not important for us now but I still added them for completeness sake.

A challenge here is writing tests for this because of the complexity of the calculations and the big amount of different possible conversion paths. This is a rough list of the paths that exist:

  • "A to B" and "B to A" tags
    • IccLut8TagDataEntry
      • Input IccLut[], Clut, Output IccLut[]
      • Matrix(3x3), Input IccLut[], IccClut, Output IccLut[]
    • IccLut16TagDataEntry
      • Input IccLut[], IccClut, Output IccLut[]
      • Matrix(3x3), Input IccLut[], IccClut, Output IccLut[]
    • IccLutAToBTagDataEntry/IccLutBToATagDataEntry (Curve types can either be IccCurveTagDataEntry or IccParametricCurveTagDataEntry (which has several curve subtypes))
      • CurveA[], Clut, CurveM[], Matrix(3x1), Matrix(3x3), CurveB[]
      • CurveA[], Clut, CurveB[]
      • CurveM[], Matrix(3x1), Matrix(3x3), CurveB[]
      • CurveB[]
  • "D to B" tags
    • IccMultiProcessElementsTagDataEntry that contains an array of any of those types in any order:
      • IccCurveSetProcessElement
        • IccOneDimensionalCurve[] where each curve can have several curve subtypes
      • IccMatrixProcessElement
        • Matrix(Nr. of input Channels by Nr. of output Channels), Matrix(Nr. of output channels by 1)
      • IccClutProcessElement
        • IccClut
  • Color Trc
    • Matrix(3x3), one curve for R, G and B each (Curve types can either be IccCurveTagDataEntry or IccParametricCurveTagDataEntry (which has several curve subtypes))
  • Gray Trc
    • Curve (Curve type can either be IccCurveTagDataEntry or IccParametricCurveTagDataEntry (which has several curve subtypes))

The three main approaches in that list are

  • A to B/B to A: using a combination of lookup tables, matrices and curves
  • D to B: using a chain of multi process elements (curves, matrices or lookup)
  • Trc: using curves (and matrices for color but not for gray)

The most used approaches are Color Trc for RGB profiles and LutAToB/LutBToA for CMYK profiles.

Todo list:

  • Integrate with the rest of the project
  • Write tests that cover all conversion paths
  • Review architecture
  • Improve speed and accuracy of the calculations

Help and suggestions are very welcome.

@brianpopow
Copy link
Collaborator

I wonder why the test MatrixCalculator_WithMatrix_ReturnsResult only fails with netcoreapp2.1 and not with the other frameworks.

@JimBobSquarePants
Copy link
Member Author

@brianpopow It'll be an accuracy issue most likely. (I hope it's not a JIT issue). It should be possible to inspect the result and see.

@codecov
Copy link

codecov bot commented Jul 13, 2021

Codecov Report

❗ No coverage uploaded for pull request base (main@ca20c92). Click here to learn what that means.
The diff coverage is n/a.

❗ Current head 5834c39 differs from pull request most recent head f60d4b8. Consider uploading reports for the commit f60d4b8 to get more accurate results

@@          Coverage Diff           @@
##             main   #1567   +/-   ##
======================================
  Coverage        ?     87%           
======================================
  Files           ?    1023           
  Lines           ?   55212           
  Branches        ?    7052           
======================================
  Hits            ?   48227           
  Misses          ?    5768           
  Partials        ?    1217           
Flag Coverage Δ
unittests 87% <0%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

📣 We’re building smart automated test selection to slash your CI/CD build times. Learn more

@brianpopow
Copy link
Collaborator

@brianpopow It'll be an accuracy issue most likely. (I hope it's not a JIT issue). It should be possible to inspect the result and see.

The issue only happens with a Release build. I think i found the reason, but it seems very weird. Vector3.Zero does not have the expected value (0, 0, 0).

This can be seen with the testoutput:

[xUnit.net 00:00:07.19]     MatrixCalculator_WithMatrix_ReturnsResult(matrix2D: { {M11:1 M12:0 M13:0 M14:0} {M21:0 M22:1 M23:0 M24:0} {M31:0 M32:0 M33:1 M34:0} {M41:0 M42:0 M43:0 M44:1} }, matrix1D: <-0,0007887525. 4,590794E-41. 1>, input: <0,5. 0,5. 0,5. 0>, expected: <0,5. 0,5. 0,5. 0>) [FAIL]

matrix1D is supposed to be Vector3.Zero

@JimBobSquarePants
Copy link
Member Author

Vector3.Zero does not have the expected value (0, 0, 0).

@brianpopow Woah! That's bonkers!

@brianpopow
Copy link
Collaborator

Vector3.Zero does not have the expected value (0, 0, 0).

@brianpopow Woah! That's bonkers!

I have reported this issue: dotnet/runtime#55623

They confirmed the issue, but they say its unlikely to be fixed because netcore2.1 is out of support in august.
So long story short: be careful with default values or Vector.Zero in testdata.

@brianpopow
Copy link
Collaborator

@JimBobSquarePants It would be really nice, if we could bring this PR forward. This would be a good addition to ImageSharp. I thought, I may ask you, if you know what the PR needs (besides tests) to be finished?

What would be the right way to apply an embedded color profile? My first attempt was:

var converter = new IccPcsToDataConverter(profile);
for (int y = 0; y < image.Height; y++)
{
    for (int x = 0; x < image.Width; x++)
    {
        var inputVec = image[x, y].ToVector4();
        Vector4 converted = converter.Calculate(inputVec);
        image[x, y] = new RgbaVector(converted.X, converted.Y, converted.Z);
    }
}

Here is an example image with adobe rgb color profile:

Momiji-AdobeRGB-yes

This does not seems to work, the colors seem to be wrong. Here are more example images

@JimBobSquarePants
Copy link
Member Author

@brianpopow Honestly.....

I don't know. I was hoping the OP would come back to finish things off. I've just kept things updated over the years and hadn't gotten involved at all in the implementation as yet.

Judging from the old comments in the previous PR I believe the code is based somewhat based on the following

https://github.com/InternationalColorConsortium/DemoIccMAX/tree/master/IccProfLib

As for accuracy. That result looks like it's just spitting out the sRGB values again.

I do agree that it would be an awesome addition to the library and would save a ton of headaches. I hoped we'd get it in V3 but that's a mighty big ask.

@brianpopow
Copy link
Collaborator

I think we definitely need a reference implementation to compare the results against. I tried BABL which gnome is using, but i could not get it to work on windows. I will take a look at DemoIccMAX

@waacton
Copy link
Collaborator

waacton commented Feb 9, 2025

I added support for TRC conversions in Unicolour at the start of the year which has unearthed a couple of extra discrepancies, probably related to PCS adjustment again. Once I've figured that out I'd feel confident saying that ICC conversion is working (to the best of our knowledge, for specific rendering intents).

@waacton
Copy link
Collaborator

waacton commented Feb 13, 2025

@JimBobSquarePants the ICC conversion tests are now working as far as I'm concerned, I don't think the current build failures are related.

Testing summary

  • Profile-to-profile conversions covering permutations of
    • v2 & v4 profiles
    • CMYK & RGB data spaces
    • Lut8, Lut16, LutAB, TRC transformations
  • Covers boundary cases, values that trigger specific perceptual adjustment branching, and random values
  • I've run all profile pairings using random values one million times each locally, all passed

Known issues

  • No testing for BToD / DToB tags (no reason to think it will be incorrect but not yet implemented in Unicolour, and I don't have any profiles with those tags)
  • No testing for GRAY data colour space (I don't think ImageSharp has a suitable 1D data structure?)
  • Profile with absolute intent will calculate incorrect values (needs its own form of PCS adjustment that will increase complexity a lot, and I don't have any profiles that reference it)
  • No testing for profile with saturation intent (no reason to think it will be incorrect, but I don't have any profiles that reference it)
  • Only working and tested with ConvertUsingIccProfile(TFrom source) - the ConvertUsingIccProfile(ReadOnlySpan<TFrom> source, Span<TTo> destination) variant needs to be updated and tested (beyond my current understanding)

Other than that last point, I don't think it would be unreasonable to release a first implementation with those known limitations, with some detection and error reporting.

@JimBobSquarePants
Copy link
Member Author

@waacton You’re a wizard!! I’ll have a look at your updates then look at updating the bulk code to match.

@waacton
Copy link
Collaborator

waacton commented Feb 14, 2025

I lie awake at night wondering if I've misinterpreted something with the DemoIccMAX reference implementation or the ICC spec (there's too much for a mere mortal like me to unpack), and if everything I've done here and in my own library is wrong 🫠

Quick note for the DToB / BToD tags, I eventually want to use this probe v2 profile as a smoke test for them. These multi-process elements are so flexible that testing every possible path through them would be a nightmare, and I suspect there's very little real-world data available. The probe profile wouldn't test complex tags, but the results should be predictable and might even be a nice visual confirmation for ImageSharp.

@saucecontrol
Copy link
Contributor

DirectX includes an scRGB profile with DToB/BToD tags, which they use to increase the precision of the RGB<->XYZ matrices. It makes for a good test because it should match a linear sRGB profile very closely.

d2d_scRGB.zip

I can also dig up some greyscale profiles if that would be helpful.

@waacton
Copy link
Collaborator

waacton commented Feb 15, 2025

... if everything I've done here and in my own library is wrong 🫠

I'll put the brakes on my celebrations for now; I updated my test-data-generation code with the latest code from the ICC reference implementation, and now I have 40,000+ failing tests 🙃

I don't have the energy to debug what's changed but since ImageSharp is a port of the reference implementation from an earlier time then presumably it's either A) something I've introduced to ImageSharp (e.g. the PCS adjustment routine is now wrong) or B) the reference implementation has changed, and both Unicolour and ImageSharp underlying implementations are wrong.

Either way, I've raised an issue to try to find out more: InternationalColorConsortium/DemoIccMAX#113

@waacton
Copy link
Collaborator

waacton commented Apr 8, 2025

@JimBobSquarePants the ICC conversion tests are now working as far as I'm concerned, I don't think the current build failures are related.

Testing summary

  • Profile-to-profile conversions covering permutations of

    • v2 & v4 profiles
    • CMYK & RGB data spaces
    • Lut8, Lut16, LutAB, TRC transformations
  • Covers boundary cases, values that trigger specific perceptual adjustment branching, and random values

  • I've run all profile pairings using random values one million times each locally, all passed

Known issues

  • No testing for BToD / DToB tags (no reason to think it will be incorrect but not yet implemented in Unicolour, and I don't have any profiles with those tags)
  • No testing for GRAY data colour space (I don't think ImageSharp has a suitable 1D data structure?)
  • Profile with absolute intent will calculate incorrect values (needs its own form of PCS adjustment that will increase complexity a lot, and I don't have any profiles that reference it)
  • No testing for profile with saturation intent (no reason to think it will be incorrect, but I don't have any profiles that reference it)
  • Only working and tested with ConvertUsingIccProfile(TFrom source) - the ConvertUsingIccProfile(ReadOnlySpan<TFrom> source, Span<TTo> destination) variant needs to be updated and tested (beyond my current understanding)

Other than that last point, I don't think it would be unreasonable to release a first implementation with those known limitations, with some detection and error reporting.

The issue I encountered in February with test data not matching DemoIccMAX seems to be resolved (and a reasonably chance it wasn't a real issue in the first place), so I'm back to believing the above summary.

@JimBobSquarePants
Copy link
Member Author

@JimBobSquarePants the ICC conversion tests are now working as far as I'm concerned, I don't think the current build failures are related.
Testing summary

  • Profile-to-profile conversions covering permutations of

    • v2 & v4 profiles
    • CMYK & RGB data spaces
    • Lut8, Lut16, LutAB, TRC transformations
  • Covers boundary cases, values that trigger specific perceptual adjustment branching, and random values

  • I've run all profile pairings using random values one million times each locally, all passed

Known issues

  • No testing for BToD / DToB tags (no reason to think it will be incorrect but not yet implemented in Unicolour, and I don't have any profiles with those tags)
  • No testing for GRAY data colour space (I don't think ImageSharp has a suitable 1D data structure?)
  • Profile with absolute intent will calculate incorrect values (needs its own form of PCS adjustment that will increase complexity a lot, and I don't have any profiles that reference it)
  • No testing for profile with saturation intent (no reason to think it will be incorrect, but I don't have any profiles that reference it)
  • Only working and tested with ConvertUsingIccProfile(TFrom source) - the ConvertUsingIccProfile(ReadOnlySpan<TFrom> source, Span<TTo> destination) variant needs to be updated and tested (beyond my current understanding)

Other than that last point, I don't think it would be unreasonable to release a first implementation with those known limitations, with some detection and error reporting.

The issue I encountered in February with test data not matching DemoIccMAX seems to be resolved (and a reasonably chance it wasn't a real issue in the first place), so I'm back to believing the above summary.

Thanks @waacton that's greatly appreciated!

I do plan on looking at this and updating the bulk version to adopt your changes, I'm just struggling with my current workload.

I don't know what to do regarding grayscale. We have two grayscale pixel formats but no representative color for the converter. I'm not sure how one would actually work tbh given that there are several luminance BT* offerings, we use 709 for Rgba32/L(8|16) conversion.

@JimBobSquarePants
Copy link
Member Author

@waacton actually... We do have a failure, any idea what is going on here?

CanConvertIccProfiles(sourceProfile: "Coated_Fogra39L_VIGC_300.icc", targetProfile: "JapanColor2003WebCoated.icc", tolerance: 5.0000000000000002E-05) [FAIL]

@waacton
Copy link
Collaborator

waacton commented Apr 9, 2025

@waacton actually... We do have a failure, any idea what is going on here?

CanConvertIccProfiles(sourceProfile: "Coated_Fogra39L_VIGC_300.icc", targetProfile: "JapanColor2003WebCoated.icc", tolerance: 5.0000000000000002E-05) [FAIL]

👀 interesting, I'll try to take a look this week - a quick guess is that it might be the conversion of the random colour being a little out of expected tolerance.

@JimBobSquarePants
Copy link
Member Author

@waacton I think I've correctly ported the bulk conversion code based upon your implementation. Would it be possible for you to check it for me?

@waacton
Copy link
Collaborator

waacton commented Apr 30, 2025

@waacton I think I've correctly ported the bulk conversion code based upon your implementation. Would it be possible for you to check it for me?

That was fast! I'll happily take a look, will aim to before the end of this week. Any hints on how to trigger these bulk conversions, to speed things along when I get a moment? I'll probably try to get them wrapped in tests if they aren't already.

@JimBobSquarePants
Copy link
Member Author

@waacton I think I've correctly ported the bulk conversion code based upon your implementation. Would it be possible for you to check it for me?

That was fast! I'll happily take a look, will aim to before the end of this week. Any hints on how to trigger these bulk conversions, to speed things along when I get a moment? I'll probably try to get them wrapped in tests if they aren't already.

Thanks, much appreciated!

I think the best bet is to write tests similar to the ones you wrote but with spans with repeating patterns of a single color. Then you can compare by looping the reference implementation if it doesn't already have bulk conversion methods.

@waacton
Copy link
Collaborator

waacton commented May 3, 2025

@JimBobSquarePants the bulk conversion code makes sense to me (with the caveat that I'm not familiar with SIMD stuff), just one sneaky bug in the PCS-to-v2-black-point code that's been fixed.

The tests I added for bulk conversion that work with Span are unlikely to be following best practice, so worth checking over that when you get a chance.

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

Successfully merging this pull request may close these issues.

9 participants