2

I am loading a volume from a dicom folder

import SimpleITK as sitk
reader = sitk.ImageSeriesReader()
dicom_names = reader.GetGDCMSeriesFileNames(input_dir)
reader.SetFileNames(dicom_names)
image = reader.Execute()

, and I am getting the following warning. Is it possible to catch this warning?

WARNING: In d:\a\1\work\b\itk-prefix\include\itk-5.1\itkImageSeriesReader.hxx, line 480
ImageSeriesReader (000002C665417450): Non uniform sampling or missing slices detected,  maximum nonuniformity:292.521

I have tried the solutions from this question and it does not work. Is it because the warning message is coming from the C code?

Sep
  • 347
  • 3
  • 13

1 Answers1

1

As the warning generated from C++ code cannot be caught in python, I came up with a workaround/hack, which does not depend on a warning object. The solution is based on redirecting sys.stderr of the code that can generate a warning to a file and checking the file for the "warning" keyword.

The context manager code based on this answer.

import sys
from contextlib import contextmanager

def flush(stream):
    try:
        libc.fflush(None)
        stream.flush()
    except (AttributeError, ValueError, IOError):
        pass  # unsupported


def fileno(file_or_fd):
    fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
    if not isinstance(fd, int):
        raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
    return fd


@contextmanager
def stdout_redirected(to=os.devnull, stdout=None):
    if stdout is None:
       stdout = sys.stdout

    stdout_fd = fileno(stdout)
    # copy stdout_fd before it is overwritten
    # Note: `copied` is inheritable on Windows when duplicating a standard stream
    with os.fdopen(os.dup(stdout_fd), 'wb') as copied:
        # stdout.flush()  # flush library buffers that dup2 knows nothing about
        # stdout.flush() does not flush C stdio buffers on Python 3 where I/O is
        # implemented directly on read()/write() system calls. To flush all open C stdio
        # output streams, you could call libc.fflush(None) explicitly if some C extension uses stdio-based I/O:
        flush(stdout)
        try:
            os.dup2(fileno(to), stdout_fd)  # $ exec >&to
        except ValueError:  # filename
            with open(to, 'wb') as to_file:
                os.dup2(to_file.fileno(), stdout_fd)  # $ exec > to
        try:
            yield stdout  # allow code to be run with the redirected stdout
        finally:
            # restore stdout to its previous value
            # Note: dup2 makes stdout_fd inheritable unconditionally
            # stdout.flush()
            flush(stdout)
            os.dup2(copied.fileno(), stdout_fd)  # $ exec >&copied

Detecting warning generated by the C++ code:

import SimpleITK as sitk

with open('output.txt', 'w') as f, stdout_redirected(f, stdout=sys.stderr):
    reader = sitk.ImageSeriesReader()
    dicom_names = reader.GetGDCMSeriesFileNames(input_dir)
    reader.SetFileNames(dicom_names)
    image = reader.Execute()

with open('output.txt') as f:
    content = f.read()
if "warning" in content.lower():
    raise RuntimeError('SimpleITK Warning!')
Sep
  • 347
  • 3
  • 13