I have two instances of cv::Mat : m1 and m2. They are of the same numeric type and sizes. Is there any function in OpenCV that returns whether the matrices are identical (have all the same values)?
For any two matrices to be equal, a number of rows and columns in both the matrix should be equal and the corresponding elements should also be equal.
Algorithm. Step 1: Create two matrix. Step 2: Then traverse every element of the first matrix and second matrix and compare every element of the first matrix with the second matrix. Step 3: If the both are same then both matrices are identical.
If both matrix elements and size are equal, then it displays that the two matrices are equal. If size of matrix is equal but the elements are not equal, then it displays that the matrix can be compared but is not equal. If the size and elements are not matched, then it displays that the matrices cannot be compared.
Approach. Iterate both matrices a[i][j] and b[i][j], and check a[i][j]==b[i][j] if true for all then print they are identical else print they are not identical.
They are of the same numeric type and sizes. Is there any function in OpenCV that returns whether the matrices are identical (have all the same values)? Show activity on this post.
The below program checks if two square matrices of size 4*4 are identical or not. For any two matrices to be equal, a number of rows and columns in both the matrix should be equal and the corresponding elements should also be equal. Recommended: Please solve it on “ PRACTICE ” first, before moving on to the solution.
But only if you apply the principles laid out in these programs. Two matrices are said to be identical if both of them have the same number of rows, columns, and the same corresponding elements. In this article, you'll learn how to check if two matrices are identical using Python, C++, JavaScript, and C.
If you need to check if 2 cv::Mat are equal, you can perform the AND XOR operator and check if the result is a cv::Mat full of zeros: Show activity on this post. The AND operator is not the good one for this task. If a matrix is all 0, it will always return true regardless if the other matrix is all 0 or not. The XOR must be used in this case.
As mentioned by Acme, you can use cv::compare
although it is not as clean as you might hope.
In the following example, cv::compare
is called by using the !=
operator:
// Get a matrix with non-zero values at points where the // two matrices have different values cv::Mat diff = a != b; // Equal if no elements disagree bool eq = cv::countNonZero(diff) == 0;
Presumably it would be quicker to just iterate through comparing the elements though? If you know the type you could use the STL equal function:
bool eq = std::equal(a.begin<uchar>(), a.end<uchar>(), b.begin<uchar>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With