c++functionopencvbyval

c++ function call by value not work


I have a problem with this code:

The problem is when I see the image original, is modified by "borrarFondo()" but this function is called from "segmentarHoja" and here entry img by value, but img modifies.

void borrarFondo(Mat& img){
   img = ~img;
   Mat background;
   medianBlur(img, background, 45);
   GaussianBlur(background, background, Size(203,203),101,101);
   img = img - background;
   img = ~img;
}

void segmentarHoja(Mat img, Mat& imsheet){
   Mat imgbw;
   borrarFondo(img); //borrarFondo is called from here where img is a copy
   cvtColor(img, imgbw, CV_BGR2GRAY);
   threshold(imgbw, imgbw, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
   Mat element = getStructuringElement(MORPH_ELLIPSE, Size(21,21));
   erode(imgbw, imgbw, element);
   vector<vector<Point> > contoursSheet; 
   findContours(imgbw, contoursSheet, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
   vector<Rect> boundSheet(contoursSheet.size());
   int largest_area=0;

   for( int i = 0; i< contoursSheet.size(); i++ )
   {
        double a= contourArea( contoursSheet[i],false);
        if(a>largest_area){
           largest_area=a; 
           boundSheet[i] = boundingRect(contoursSheet[i]);
           imsheet=img(boundSheet[i]).clone(); 
        }
    }
    borrarFondo(imsheet);
  }

int main()
{
    Mat imsheet;
    image= imread("c:/imagen.jpg");
    segmentarHoja(image, imsheet);

    imshow("imsheet",imsheet);
    imshow("imagen",image); //original image by amending borrarFondo 
    waitKey(0);
}

I don't want to change original image


Solution

  • opencv Mat is a counted reference (i.e. like std::shared_ptr, except different syntax) where copy construction or assignment does not copy. use the clone method to copy. read the documentation, always a good idea.