Search code examples
pythonwarningsscikit-image

Catching Warnings in Function skimage.img_as_uint


I tried both warnings.catch_warnings() and the input parameter force_copy both failed to catch conversion warnings

import numpy as np
import skimage
import warnings

mm = np.ones([55,55],dtype=np.float32)
with warnings.catch_warnings():
     dd = skimage.img_as_uint(mm,force_copy=True)

gives

XXX/lib/python2.7/site-packages/skimage/util/dtype.py:130: UserWarning: Possible precision loss
when converting from float32 to uint16.format(dtypeobj_in, dtypeobj_out))


Solution

  • You need to add a line, warnings.simplefilter('ignore'):

    import numpy as np
    import skimage
    import warnings
    
    mm = np.ones([55,55],dtype=np.float32)
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        dd = skimage.img_as_uint(mm,force_copy=True)
    

    See the Python documentation for "temporarily suppressing warnings" for more information.