在函数中捕获警告 skimage.img_as_uint

Catching Warnings in Function skimage.img_as_uint

我尝试了 warnings.catch_warnings() 和输入参数 force_copy 都未能捕捉到转换警告

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)

给予

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))

您需要添加一行,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)

有关详细信息,请参阅 Python documentation for "temporarily suppressing warnings"