Ask Your Question

comparing two image

asked 2017-10-03 14:38:25 -0500

Berkay gravatar image

updated 2017-10-03 14:40:53 -0500

Hi, ı want to compare two images and if there is any difference ı want to get 1 or 0 in C++ language like this video

difference = cv2.subtract(img1,img2);

in C++ above code does not give any integer value, what should ı write instead of this code?

edit retag flag offensive close merge delete

1 answer

Sort by » oldest newest most voted

answered 2017-10-03 15:03:44 -0500

tham gravatar image

updated 2017-10-03 17:09:41 -0500

If you are using c++, cv::subtract give you a Mat with tons of pixels value but not a single value which tell you how many non zero pixels in the matrix. You can call countNonZero in c++ to count the number of non zero pixels.

auto const diff= img1 != img2;
if(countNonZero(dst) == 0){
    cout<<"this is same picture"<<endl;
    cout<<"this is not the same picture"<<endl;

You can use stl algorithm and iterator to do the comparison too. I do not know which one is faster, you better run some test on it.

bool const equal = std::equal(img1.begin<uchar>(), img1.end<uchar>(), img2.begin<uchar>());

If you want to compare similarity of images with different size, try out img_hash module of opencv_contrib.

Edit : I replace subtraction by comparison, it is easier to read and avoid the problem of value clip.

edit flag offensive delete link more


this code can be builded but when ı work it, a fatal error happens

Berkay gravatar imageBerkay ( 2017-10-03 16:23:28 -0500 )edit

Please post your error messages, are you sure you load the image successful? Are both of the images have the same size,channels and types?

tham gravatar imagetham ( 2017-10-03 17:05:04 -0500 )edit

using namespace cv; using namespace std;

int main(){

    Mat img1,img2,dst;
VideoCapture capture(0); // kamera aç


        return -1;;; 


    if(countNonZero(dst) == 0){
          cout<<"there is no motion"<<endl;

          cout<<"there is a motion"<<endl;


    if (waitKey(30) == 27) 
               cout << "ESC key is pressed by user" << endl;
  return 0;


my purpose is to perceive when any motion occour in camera

Berkay gravatar imageBerkay ( 2017-10-04 11:12:23 -0500 )edit

Question Tools

1 follower


Asked: 2017-10-03 14:38:25 -0500

Seen: 5,869 times

Last updated: Oct 03 '17