1

I generate monochromatic images and save them using imageio.imwrite. Every time I save a file I get a following warning:

WARNING:root:Lossy conversion from float64 to uint8. Range [-0.24890179009891278, 2.35786261304524]. Convert image to uint8 prior to saving to suppress this warning.

I don't care for this "lossy conversion". Everything looks well and works fine.

However, every ~100 generated images I got different warning which I want to catch. Thus I want to ignore the above one.

I tried to ignore it, but even if I call

import warnings
warnings.simplefilter('ignore')

beforehand I still get this warning.

Fallen Apart
  • 723
  • 8
  • 20

2 Answers2

7

The library doesn't use the warnings module. Instead, it logs a message using the logging framework, by calling the top-level logging.warning() function. See the imageio.core.util._precision_warn() function:

from logging import warning as warn

# ...

def _precision_warn(p1, p2, extra=""):
    t = (
        "Lossy conversion from {} to {}. {} Convert image to {} prior to "
        "saving to suppress this warning."
    )
    warn(t.format(p1, p2, extra, p2))

This is... unfortunate, as you can't easily disable this using the logging API. Best practice is to use a dedicated named logger for libraries.

As such, it is probably best to patch the library no make the above function a no-op:

import imageio.core.util

def silence_imageio_warning(*args, **kwargs):
    pass

imageio.core.util._precision_warn = silence_imageio_warning

You could also silence all logging, adjusting configurion on the root logger. This is not ideal, as you may want to use logging yourself or use third-party libraries that are better behaved.

I've filed an issue with the project to ask them to fix their logging story.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

There is a simple workaround/solution to this. The library is using logging module and not the warning module. One can include these lines in the code to suppress any such root warnings unless it is of severity level ERROR.

import logging
logging.getLogger().setLevel(logging.ERROR)

Had it not been a root warning, one could use the following snippet instead.

import warnings
warnings.filterwarnings("ignore")
Nikhil K.
  • 161
  • 9