how to check whether two matrices are identical in OpenCV

前端 未结 9 1792
南方客
南方客 2020-11-28 10:44

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 (ha

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 11:00

    As mentioned by Acme and Tim, you can use cv::compare. This is the code I use to compare my cv::Mat:

     bool 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;
    }
    

    It is important to stand out that the function cv::countNonZero only works with cv::Mat of one channel, so if you need to compare two cv::Mat images, you need first to convert your cv::Mat in this way:

    Mat gray1, gray2;
    cvtColor(InputMat1, gray1, CV_BGR2GRAY);
    cvtColor(InputMat2, gray2, CV_BGR2GRAY);
    

    where InputMat1 and InputMat2 are the cv::Mat you want to compare. After that you can call the function:

    bool equal = matsEqual(gray1, gray2);
    

    I took this code of this site: OpenCV: compare whether two Mat is identical

    I hope this help you.

提交回复
热议问题