python – numpy: Invalid value encountered in true_divide
python – numpy: Invalid value encountered in true_divide
You may have a NAN
, INF
, or NINF
floating around somewhere. Try this:
np.isfinite(diff_images).all()
np.isfinite(b_0).all()
If one or both of those returns False
, thats likely the cause of the runtime error.
The reason you get the runtime warning when running this:
log_norm_images = np.where(b_0 > 0, np.divide(diff_images, b_0), 0)
is that the inner expression
np.divide(diff_images, b_0)
gets evaluated first, and is run on all elements of diff_images
and b_0
(even though you end up ignoring the elements that involve division-by-zero). In other words, the warning happens before the code that ignores those elements. That is why its a warning and not an error: there are legitimate cases like this one where the division-by-zero is not a problem because its being handled in a later operation.
python – numpy: Invalid value encountered in true_divide
Another useful Numpy command is nan_to_num(diff_images)
By default it replaces in a Numpy array; NaN to zero, -INF to -(large number) and +INF to +(large number)
You can change the defaults, see https://numpy.org/doc/stable/reference/generated/numpy.nan_to_num.html