Ask Your Question
-1

comparing two image

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

Berkay gravatar image

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

Hi, ı want to compare two images and if there is any difference ı want to get 1 or 0 in C++ language like this video https://www.youtube.com/watch?v=LNzC4...

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
1

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

tham gravatar image

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

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;
}else{
    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

Comments

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

Berkay gravatar imageBerkay ( 2017-10-03 16:23:28 -0600 )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 -0600 )edit

using namespace cv; using namespace std;

int main(){

    Mat img1,img2,dst;
VideoCapture capture(0); // kamera aç
namedWindow("Camera",1);
Sleep(500);

while(1){

    if(!capture.isOpened())
        return -1;

    capture.read(img1); 
    capture.read(img2); 

    absdiff(img1,img2,dst);

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

   else{
          cout<<"there is a motion"<<endl;
    }

    imshow("Camera",img1);

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

}

my purpose is to perceive when any motion occour in camera

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

Question Tools

1 follower

Stats

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

Seen: 7,075 times

Last updated: Oct 03 '17