Saturday, February 23, 2013

OpenCV: compare whether two Mat is identical

As MATLAB users could always conveniently compare two matrix, in order to decide whether the two matrix is identical or not.
However, in OpenCV this easy task is not straight forward as you first thought.
The underlying small openCV script could help you to address this simple task.

// return true if two matrix is identical, false otherwise


bool BasicUtil::matIsEqual(const cv::Mat mat1, const cv::Mat mat2){
    // treat two empty mat as identical as well
    if (mat1.empty() && mat2.empty()) {
        return true;
    }
    // if dimensionality of two mat is not identical, these two mat is not identical
    if (mat1.cols != mat2.cols || mat1.rows != mat2.rows || mat1.dims != mat2.dims) {
        return false;
    }
    cv::Mat diff;
    cv::compare(mat1, mat2, diff, cv::CMP_NE);
    int nz = cv::countNonZero(diff);
    return nz==0;
}


PS: I'm currently building a C++ toolbox in order to replace some basic MATLAB functionality for computer vision users. I will release it once I built a considerable functionalities.

4 comments:

  1. Hi
    I was trying to use your function but I was getting: Assertion failed (src.channels() == 1 && func != 0) in countNonZero.
    Is it possible that you need to convert diff to one channel before calling countNonZero ?
    here is the modified code I am using:
    cv::Mat diff; cv::Mat diff1color;
    cv::compare(mat1, mat2, diff, cv::CMP_NE);
    cv::cvtColor(diff, diff1color, CV_BGRA2GRAY, 1);

    int nz = cv::countNonZero(diff1color);
    Regards, Nicolas.

    ReplyDelete
  2. So how many functions have you done? maybe I can contribute some...

    ReplyDelete
  3. If you are using C++, you can actually use the nature of the cv::Mat object, which allows you to use iterators:

    std::equal(img1.begin(), img1.end(), img2.begin())

    The std::equal() returns 0 if the two are equal and 1 if they are not.

    Even though the cv::countNonZero() does work in many cases, there are some where counting for zeroes is not rock-solid. With the iteration and comparing of each element you do make sure that the two matrices have different elements. Of course here we assume the same size for both!

    ReplyDelete
  4. can you please share same for java

    ReplyDelete

prettify