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

Fix bioformats processing of MONOCHROME1 dicom data #1834

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
### Changes

- Require a minimum version of Pillow to avoid a CVE ([#1828](../../pull/1828))
- Work around how bioformats handles DICOMs in Monochrome1 ([#1834](../../pull/1834))

## 1.31.1

Expand Down
37 changes: 37 additions & 0 deletions sources/bioformats/large_image_source_bioformats/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@
delattr(self, '_lastGetTileException')
except Exception as exc:
raise TileSourceError('Bioformats cannot read a tile: %r' % exc)
self._checkForOffset()
self._populatedLevels = len([
v for v in self._metadata['frameSeries'][0]['series'] if v is not None])

Expand All @@ -348,6 +349,40 @@
if javabridge.get_env():
javabridge.detach()

def _checkForOffset(self):
"""
The bioformats DICOM reader does unfortunate things to MONOCHROME1
16-bit images. Store an offset to undo it, if appropriate.
"""
if self._metadata.get('readerClassName') != 'loci.formats.in.DicomReader':
return
if self._metadata.get('seriesMetadata', {}).get(
'0028,0004 Photometric Interpretation') != 'MONOCHROME1':
return
if np.issubdtype(self.dtype, np.uint8):
self._fix_offset = 255
return

Check warning on line 364 in sources/bioformats/large_image_source_bioformats/__init__.py

View check run for this annotation

Codecov / codecov/patch

sources/bioformats/large_image_source_bioformats/__init__.py#L363-L364

Added lines #L363 - L364 were not covered by tests
if not np.issubdtype(self.dtype, np.int16) and not np.issubdtype(self.dtype, '>i2'):
return

Check warning on line 366 in sources/bioformats/large_image_source_bioformats/__init__.py

View check run for this annotation

Codecov / codecov/patch

sources/bioformats/large_image_source_bioformats/__init__.py#L366

Added line #L366 was not covered by tests
# This is bioformats behavior
try:
maxPixelRange = int(self._metadata['seriesMetadata'].get(
'0028,1051 Window Width', 0))
except Exception:
maxPixelRange = -1
try:
centerPixelValue = int(self._metadata['seriesMetadata'].get(
'0028,1050 Window Center', 0))
except Exception:
centerPixelValue = -1
maxPixelValue = maxPixelRange + (centerPixelValue // 2)
maxAllowRange = 2 ** int(self._metadata['seriesMetadata'].get(
'0028,0101 Bits Stored', 16)) - 1
if maxPixelRange == -1 or centerPixelValue < maxPixelRange // 2:
maxPixelValue = maxAllowRange
if maxPixelValue:
self._fix_offset = maxPixelValue

def _metadataForCurrentSeries(self, rdr):
self._metadata = getattr(self, '_metadata', {})
self._metadata.update({
Expand Down Expand Up @@ -710,6 +745,8 @@
retile[0:min(tile.shape[0], finalHeight), 0:min(tile.shape[1], finalWidth)] = tile[
0:min(tile.shape[0], finalHeight), 0:min(tile.shape[1], finalWidth)]
tile = retile
if hasattr(self, '_fix_offset') and format == TILE_FORMAT_NUMPY:
tile = self._fix_offset - tile
return self._outputTile(tile, format, x, y, z, pilImageAllowed, numpyAllowed, **kwargs)

def getAssociatedImagesList(self):
Expand Down
4 changes: 4 additions & 0 deletions test/datastore.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,10 @@
# --rgb --quality=0.015 --compression='JPEG-2000 Lossy' parameters to make
# the file small
'TCGA-55-8207-01Z-00-DX1.ome.tiff': 'sha512:50cf63f0e8bfa3054d3532b7dd0237b66aeb4c7609da874639a28bc068dbd157f786e84d3eb76a3b0e6636a042c56c3b96d3be2ad66f7589d0542a5d20cecdb4', # noqa
# Extracted from a sample dicom file from issue #1823 on github
# This is a dicom with monochrome1 format data that bioformats incorrectly
# inverts and offsets
'monochrome1.dcm': 'sha512:a67c38a5e26aba31b68e40eec0f260acf0ba638f0bf7fd99d41c3e16ddd8fd43b2737aeb3759ce92f2c4a10a81995bdae3b93b101ebcaa59543ea6eff7a4c8f2', # noqa
}


Expand Down
8 changes: 4 additions & 4 deletions test/test_source_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
'deepzoom': {},
'dicom': {
'read': r'\.dcm$',
'noread': r'tcia.*\.dcm$',
'noread': r'(tcia.*|monochrome1)\.dcm$',
},
'dummy': {'any': True, 'skipTiles': r''},
'gdal': {
Expand Down Expand Up @@ -63,7 +63,7 @@
'openjpeg': {'read': r'\.(jp2)$'},
'openslide': {
'read': r'\.(ptif|svs|ndpi|tif.*|qptiff|dcm)$',
'noread': r'(oahu|DDX58_AXL|huron\.image2_jpeg2k|landcover_sample|d042-353\.crop|US_Geo\.|extraoverview|imagej|bad_axes|synthetic_untiled|indica|tcia.*dcm|multiplane.*ndpi)', # noqa
'noread': r'(oahu|DDX58_AXL|huron\.image2_jpeg2k|landcover_sample|d042-353\.crop|US_Geo\.|extraoverview|imagej|bad_axes|synthetic_untiled|indica|tcia.*dcm|monochrome1.dcm|multiplane.*ndpi)', # noqa
'skip': r'nokeyframe\.ome\.tiff|TCGA-55.*\.ome\.tiff$',
'skipTiles': r'one_layer_missing',
},
Expand All @@ -83,14 +83,14 @@
'skipTiles': r'(sample_image\.ptif|one_layer_missing_tiles)'},
'tifffile': {
'read': r'',
'noread': r'((\.(nc|nd2|yml|yaml|json|czi|png|jpg|jpeg|jp2|zarr\.db|zarr\.zip)|(nokeyframe\.ome\.tiff|XY01\.ome\.tif|level.*\.dcm|tcia.*dcm)$)' + # noqa
'noread': r'((\.(nc|nd2|yml|yaml|json|czi|png|jpg|jpeg|jp2|zarr\.db|zarr\.zip)|(nokeyframe\.ome\.tiff|XY01\.ome\.tif|level.*\.dcm|tcia.*dcm|monochrome1.dcm)$)' + # noqa
(r'|bad_axes' if sys.version_info < (3, 9) else '') +
r')',
'skip': r'indica' if sys.version_info < (3, 9) else '^$',
},
'vips': {
'read': r'',
'noread': r'(\.(nc|nd2|yml|yaml|json|czi|png|svs|scn|zarr\.db|zarr\.zip)|tcia.*dcm)$',
'noread': r'(\.(nc|nd2|yml|yaml|json|czi|png|svs|scn|zarr\.db|zarr\.zip)|tcia.*dcm|monochrome1.dcm)$', # noqa
'skipTiles': r'(sample_image\.ptif|one_layer_missing_tiles|JK-kidney_B-gal_H3_4C_1-500sec\.jp2|extraoverview|synthetic_untiled)', # noqa
},
'zarr': {'read': r'\.(zarr|zgroup|zattrs|db|zarr\.zip)$'},
Expand Down
11 changes: 11 additions & 0 deletions test/test_source_bioformats.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import large_image

from . import utilities
from .datastore import datastore

Expand Down Expand Up @@ -31,3 +33,12 @@ def testBioformatsJarVersion():
import large_image_source_bioformats

assert '.' in large_image_source_bioformats._getBioformatsVersion()


def testBioformatsDicomMonochome1():
import large_image_source_bioformats

imagePath = datastore.fetch('monochrome1.dcm')
source = large_image_source_bioformats.open(imagePath)
img, _ = source.getRegion(format=large_image.constants.TILE_FORMAT_NUMPY)
assert img[255, 191, 0] == 618