How to remove inf values from CV Matrix?

Hi all,

Was wondering if there’s an easy way to remove +-inf (infinity) values from an OpenCV Matrix.
I tried patchNaNs(), but it appears that only works for NaN values, and inf is not a NaN:

>>> np.isnan(float("inf"))
False

It looks like someone else asked a similar question on GitHub. Their solution is to iterate through the whole matrix.
Is there an easier way?

1 Like

since this is python, you can replace values in a numpy slice:

im[im == float("inf")] = 17
1 Like

inf or nan? not finite

https://numpy.org/doc/stable/reference/generated/numpy.isfinite.html

Thanks @berak and @crackwitz.
Any solutions for C++? I should have labeled my post with C++ instead of Python, apologies.

similar concept in c++:

float inf = std::numeric_limits<float>::infinity();
// setup example data:
Mat_<float> m(3,3);
m << 1,2,inf,4,inf,6,7,inf,inf;

// mask all values with inf:
Mat mask = m==inf;

// change all inf vals to 17:
m.setTo(17, mask);

cout << m << endl;

[1, 2, 17;
 4, 17, 6;
 7, 17, 17]
1 Like