Check if Mat is zero

This seems to be a pretty stupid question for a version 4.9 :slight_smile:

Still I find only… too simple answers to it yet:

They do by checking all Mat’s elements:
either count the non-zeros or note their status.

But to determine if a Mat is zero doesn’t need that.
It suffices to stop the check when the first non-zero element is found.
That is a half the work in average.

I’m pretty sure countNonZero() and (myMat == 0) will be optimized
by vector ops?
So a method that simply iterates element by element and stops
at first non-zero will nevertheless be much slower.

The check if a matrix is zero (or is equal to some value) will be
very common, widely used.

So I wonder, what will be the most efficient code for that?

Edit:
It may be done quickly by this.
Still, you need space for a zero mat, and I’m not sure, how memcmp() does due to vector ops

have a look at cv::hasNonZero()

(added recently, after a discussion similar to yours above)

As I’m still kind of a freshman… could you please tell how cv::hasNonZero() compares to the code mentioned above?
cv::hasNonZero() is for single-channel only?
And what about that other code: Will that be correct universally?

EDIT:
Having to extract each channel (completely) for a multi-channel matrix
one-by-one would give away the optimal processing.
So…?

hasNonZero uses SIMD for faster processing. You can create 1-channel Mat header on the same data using reshape method (I assume you do not need per-channel results): OpenCV: cv::Mat Class Reference

2 Likes

And if… you wouldn’t copy the resp. channel data with split() or extractChannel (),
but use a simple pointer assignment?

I wonder about the share of misuse/ time and mem waste of split() and extractChannel() for that;
moreover about countNonZero() for cv::hasNonZero().
90% ?