shahzaib
shahzaib

Reputation: 75

How to get similarties and differences between two images using Opencv

I want to compare two images and find same and different parts of images. I tired "cv::compare and cv::absdiff" methods but confused which one can good for my case. Both show me different results. So how i can achieve my desired task ?

Upvotes: 0

Views: 5650

Answers (1)

Micka
Micka

Reputation: 20130

Here's an example how you can use cv::absdiff to find image similarities:

int main()
{
    cv::Mat input1 = cv::imread("../inputData/Similar1.png");
    cv::Mat input2 = cv::imread("../inputData/Similar2.png");

    cv::Mat diff;
    cv::absdiff(input1, input2, diff);

    cv::Mat diff1Channel;
    // WARNING: this will weight channels differently! - instead you might want some different metric here. e.g. (R+B+G)/3 or MAX(R,G,B)
    cv::cvtColor(diff, diff1Channel, CV_BGR2GRAY);

    float threshold = 30; // pixel may differ only up to "threshold" to count as being "similar"

    cv::Mat mask = diff1Channel < threshold;

    cv::imshow("similar in both images" , mask);

    // use similar regions in new image: Use black as background
    cv::Mat similarRegions(input1.size(), input1.type(), cv::Scalar::all(0));

    // copy masked area
    input1.copyTo(similarRegions, mask);


    cv::imshow("input1", input1);
    cv::imshow("input2", input2);
    cv::imshow("similar regions", similarRegions);
    cv::imwrite("../outputData/Similar_result.png", similarRegions);
    cv::waitKey(0);
    return 0;
}

Using those 2 inputs:

enter image description here

enter image description here

You'll observe that output (black background):

enter image description here

Upvotes: 3

Related Questions