Ask Your Question

Why are the two images equal?

asked 2017-04-07 12:57:33 -0500

el_cid gravatar image

updated 2017-04-07 12:59:43 -0500

in my program, main calls a function which takes two pictures with a USB camera and writes them into a vector passed by reference to it. Due to an error I'm unable to find (for 2 days now...) the two images written into the vector are identical after I return to main (I test this with the function "equal(...)"), even if they should not be the same, as they were taken with a wait time in between, and I'm waving in front of the camera. Can some of you code angels spot an error I did? The equal() function is not the problem, I have tested it thoroughly.

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/videoio/videoio.hpp>

using namespace std;

//---------FUNCTION DECLARATIONS----------------
void       takePictures(vector<cv::Mat>&);
bool       equal(const cv::Mat&, const cv::Mat&);

int main(int argc, char* argv[])

  // Take pictures
  vector<cv::Mat> images;
  takePictures( images);

  bool sameImg = equal(images[0],images[1]);

  return 0;

//----------IMAGE TAKING FUNCTION---------------
void takePictures(vector<cv::Mat>& images)
  // open cameras
  cv::VideoCapture cap1(0);
  cv::Mat img1;

  // Picture taking procedure
  for ( int i = 1; i <= 2; i++ )
    cap1 >> img1;

bool equal(const cv::Mat & a, const cv::Mat & b)
    if ( (a.rows != b.rows) || (a.cols != b.cols) )
        return false;
    cv::Scalar s = sum( a - b );
    return (s[0]==0) && (s[1]==0) && (s[2]==0);

Thank you a lot in advance for your help.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2017-04-07 13:57:55 -0500

matman gravatar image

images.push_back(imgl); is the same as cv::Mat image = imgl; and only copies the Mat header not the data.

So you are pointing both vector elements to the same data. Instead you should do a deep copy with images.push_back(imgl.clone()); for example.

edit flag offensive delete link more


Thank you, matman. I had to think a little bit, but then I understood your answer. For other people having a similar issue I try to rephrase it: By using push_back() the matrix header is stored in the two vector elements. The matrix header is (beside other stuff, see link) a pointer to the matrix data. So in the end, the images-vector is just a vector of two pointers pointing to the same matrix, img1, which at the end of the second loop is the secondly taken picture.

el_cid gravatar imageel_cid ( 2017-04-11 01:40:01 -0500 )edit
Login/Signup to Answer

Question Tools

1 follower


Asked: 2017-04-07 12:57:33 -0500

Seen: 117 times

Last updated: Apr 07 '17