ImagingDataCommons / highdicom

High-level DICOM abstractions for the Python programming language
https://highdicom.readthedocs.io
MIT License
172 stars 37 forks source link

Can't read a DicomBytesIO with ImageFileReader #222

Closed RobinFrcd closed 1 year ago

RobinFrcd commented 1 year ago

Hi, I'm trying to use ImageFileReader on a DicomBytesIO (which inherits from DicomFileLike).

from pydicom.filebase import DicomBytesIO, DicomFileLike
from highdicom.io import ImageFileReader

d = DicomBytesIO(open('/tmp/dicoms/IMG_20220714_1_247_38.dcm', 'rb').read())
print(isinstance(d, DicomFileLike))
# True
with ImageFileReader(d) as image:
    print(image.number_of_frames)

But I'm getting the following traceback:

AttributeError                            Traceback (most recent call last)
Input In [27], in <cell line: 2>()
      1 d = DicomBytesIO(open('/tmp/dicoms/IMG_20220714_1_247_38.dcm', 'rb').read())
----> 2 with ImageFileReader(d) as image:
      3     print(image.number_of_frames)
      6 dataset = dcmread(dcm)

File ~/.pyenv/versions/3.10.6/envs/dev3106/lib/python3.10/site-packages/highdicom/io.py:245, in ImageFileReader.__init__(self, filename)
    243 if isinstance(filename, DicomFileLike):
    244     fp = filename
--> 245     is_little_endian, is_implicit_VR = self._check_file_format(fp)
    246     try:
    247         if fp.is_little_endian != is_little_endian:

File ~/.pyenv/versions/3.10.6/envs/dev3106/lib/python3.10/site-packages/highdicom/io.py:356, in ImageFileReader._check_file_format(self, fp)
    334 def _check_file_format(self, fp) -> Tuple[bool, bool]:
    335     """Check whether file object represents a DICOM Part 10 file.
    336 
    337     Parameters
   (...)
    354 
    355     """
--> 356     file_meta = read_file_meta_info(str(self._filename))
    357     transfer_syntax_uid = UID(file_meta.TransferSyntaxUID)
    358     return (
    359         transfer_syntax_uid.is_little_endian,
    360         transfer_syntax_uid.is_implicit_VR,
    361     )

AttributeError: 'ImageFileReader' object has no attribute '_filename'
hackermd commented 1 year ago

Thanks for reporting the issue @RobinFrcd and apologies for the delayed feedback.

I had a quick look and it appears there is a bug that prevents reading of the File Meta Information in the _check_file_format() method.

I think it should be file_meta = read_file_meta_info(str(fp.name)) instead of file_meta = read_file_meta_info(str(self._filename))

Could you try that?

hackermd commented 1 year ago

I thought this through further. The name property will not be set to a file path (because there is no file), so we will need an additional workaround. I will make a suggestion via your PR.