Skip to content
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

Allow ICC correction to specify intent #1066

Merged
merged 1 commit into from
Feb 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
# Change Log

## 1.20.2

### Improvements
- Allow ICC correction to specify intent ([#1066](../../pull/1066))

## 1.20.1

### Bug Fixes
- Fix packaging listing various source requirements ([#1064](../../pull/1064))
- Fix packaging listing various source requirements ([#1064](../../pull/1064))

## 1.20.0

Expand Down
2 changes: 1 addition & 1 deletion docs/config_options.rst
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Configuration parameters:

- ``source_bioformats_ignored_names``, ``source_pil_ignored_names``, ``source_vips_ignored_names``: Some tile sources can read some files that are better read by other tilesources. Since reading these files is suboptimal, these tile sources have a setting that, by default, ignores files without extensions or with particular extensions. This setting is a Python regular expressions. For bioformats this defaults to ``r'(^[!.]*|\.(jpg|jpeg|jpe|png|tif|tiff|ndpi))$'``.

- ``icc_correction``: If this is True or undefined, ICC color correction will be applied for tile sources that have ICC profile information. If False, correction will not be applied. If the style used to open a tilesource specifies ICC correction explicitly (on or off), then this setting is not used.
- ``icc_correction``: If this is True or undefined, ICC color correction will be applied for tile sources that have ICC profile information. If False, correction will not be applied. If the style used to open a tilesource specifies ICC correction explicitly (on or off), then this setting is not used. This may also be a string with one of the intents defined by the PIL.ImageCms.Intents enum. ``True`` is the same as ``perceptual``.


Configuration from Python
Expand Down
2 changes: 1 addition & 1 deletion docs/tilesource_options.rst
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ A band definition is an object which can contain the following keys:

- ``axis``: if specified, keep on the specified axis (channel) of the intermediate numpy array. This is typically between 0 and 3 for the red, green, blue, and alpha channels. Only the first such value is used, and this can be specified as a base key if ``bands`` is specified.

- ``icc``: by default, sources that expose ICC color profiles will apply those profiles to the image data, converting the results to the sRGB profile. To use the raw image data without ICC profile adjustments, specify an ``icc`` value of ``false``. If the entire style is ``{"icc": false}``, the results will be the same as the default bands with only the adjustment being skipped. Similarly, if the entire style is ``{"icc": true}``, this is the same as the default style with where the adjustment is applied. Note that not all tile sources expose ICC color profile information, even if the base file format contains it.
- ``icc``: by default, sources that expose ICC color profiles will apply those profiles to the image data, converting the results to the sRGB profile. To use the raw image data without ICC profile adjustments, specify an ``icc`` value of ``false``. If the entire style is ``{"icc": false}``, the results will be the same as the default bands with only the adjustment being skipped. Similarly, if the entire style is ``{"icc": true}``, this is the same as the default style with where the adjustment is applied. Besides a boolean, this may also be a string with one of the intents defined by the PIL.ImageCms.Intents enum. ``true`` is the same as ``perceptual``. Note that not all tile sources expose ICC color profile information, even if the base file format contains it.

- ``function``: if specified, call a function to modify the resulting image. This can be specified as a base key and as a band key. Style functions can be called at multiple stages in the styling pipeline:

Expand Down
24 changes: 20 additions & 4 deletions girder/girder_large_image/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ def handleSettingSave(event):

from girder.api.rest import setResponseHeader

large_image.config.setConfig('icc_correction', bool(event.info['value']))
large_image.config.setConfig('icc_correction', event.info['value'])
large_image.cache_util.cachesClear()
gc.collect()
try:
Expand Down Expand Up @@ -373,7 +373,6 @@ def metadataSearchHandler( # noqa
constants.PluginSettings.LARGE_IMAGE_SHOW_THUMBNAILS,
constants.PluginSettings.LARGE_IMAGE_SHOW_VIEWER,
constants.PluginSettings.LARGE_IMAGE_NOTIFICATION_STREAM_FALLBACK,
constants.PluginSettings.LARGE_IMAGE_ICC_CORRECTION,
})
def validateBoolean(doc):
val = doc['value']
Expand All @@ -382,6 +381,23 @@ def validateBoolean(doc):
doc['value'] = (str(val).lower() != 'false')


@setting_utilities.validator({
constants.PluginSettings.LARGE_IMAGE_ICC_CORRECTION,
})
def validateBooleanOrICCIntent(doc):
import PIL.ImageCms

val = doc['value']
if ((hasattr(PIL.ImageCms, 'Intent') and hasattr(PIL.ImageCms.Intent, str(val).upper())) or
hasattr(PIL.ImageCms, 'INTENT_' + str(val).upper())):
doc['value'] = str(val).upper()
else:
if str(val).lower() not in ('false', 'true', ''):
raise ValidationException(
'%s must be a boolean or a named intent.' % doc['key'], 'value')
doc['value'] = (str(val).lower() != 'false')


@setting_utilities.validator({
constants.PluginSettings.LARGE_IMAGE_AUTO_SET,
})
Expand Down Expand Up @@ -486,8 +502,8 @@ def load(self, info):
curConfig = config.getConfig().get('large_image')
for key, value in (curConfig or {}).items():
large_image.config.setConfig(key, value)
large_image.config.setConfig('icc_correction', bool(Setting().get(
constants.PluginSettings.LARGE_IMAGE_ICC_CORRECTION)))
large_image.config.setConfig('icc_correction', Setting().get(
constants.PluginSettings.LARGE_IMAGE_ICC_CORRECTION))
addSystemEndpoints(info['apiRoot'])

girder_tilesource.loadGirderTileSources()
Expand Down
15 changes: 12 additions & 3 deletions large_image/tilesource/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1245,6 +1245,12 @@ def _applyICCProfile(self, sc, frame):
self._iccprofilesObjects = [None] * len(self._iccprofiles)
image = _imageToPIL(sc.image)
mode = image.mode
if hasattr(PIL.ImageCms, 'Intent'): # PIL >= 9
intent = getattr(PIL.ImageCms.Intent, str(sc.style.get('icc')).upper(),
PIL.ImageCms.Intent.PERCEPTUAL)
else:
intent = getattr(PIL.ImageCms, 'INTENT_' + str(sc.style.get('icc')).upper(),
PIL.ImageCms.INTENT_PERCEPTUAL)
if not hasattr(self, '_iccsrgbprofile'):
self._iccsrgbprofile = PIL.ImageCms.createProfile('sRGB')
try:
Expand All @@ -1253,11 +1259,14 @@ def _applyICCProfile(self, sc, frame):
'profile': self.getICCProfiles(profileIdx)
}
if mode not in self._iccprofilesObjects[profileIdx]:
self._iccprofilesObjects[profileIdx][mode] = \
self._iccprofilesObjects[profileIdx][(mode, intent)] = \
PIL.ImageCms.buildTransformFromOpenProfiles(
self._iccprofilesObjects[profileIdx]['profile'],
self._iccsrgbprofile, mode, mode)
transform = self._iccprofilesObjects[profileIdx][mode]
self._iccsrgbprofile, mode, mode,
renderingIntent=intent)
self.logger.debug(
'Created an ICC profile transform for mode %s, intent %s', mode, intent)
transform = self._iccprofilesObjects[profileIdx][(mode, intent)]

PIL.ImageCms.applyTransform(image, transform, inPlace=True)
sc.iccimage = _imageToNumpy(image)[0]
Expand Down
16 changes: 16 additions & 0 deletions test/test_source_openslide.py
Original file line number Diff line number Diff line change
Expand Up @@ -463,3 +463,19 @@ def testInternalMetadata():
source = large_image_source_openslide.open(imagePath)
metadata = source.getInternalMetadata()
assert 'openslide' in metadata


def testICCIntents():
imagePath = datastore.fetch(
# 'sample_jp2k_33003_TCGA-CV-7242-11A-01-TS1.1838afb1-9eee-'
# '4a70-9ae3-50e3ab45e242.svs')
'sample_svs_image.TCGA-DU-6399-01A-01-TS1.e8eb65de-d63e-42db-'
'af6f-14fefbbdf7bd.svs')
images = []
for opt in {False, True, 'perceptual', 'relative_colorimetric',
'absolute_colorimetric', 'saturation'}:
ts = large_image_source_openslide.open(imagePath, style={'icc': opt})
image = ts.getThumbnail()[0]
if image not in images:
images.append(image)
assert len(images) >= 2