c++opencvreference-countingopencv-mat

What does cv::Mat's deallocate method do?


The following code

int main(int argc, char** argv)
{
  cv::Mat1b i1(cv::Size(1, 2));
  i1.at<uchar>(0, 0) = 1;
  i1.at<uchar>(1, 0) = 1;

  cv::Mat1b mask(i1.size());
  mask.at<uchar>(0, 0) = 1;
  mask.at<uchar>(1, 0) = 0;

  cv::Mat1b masked;
  mask.copyTo(masked, mask);

  masked.release(); //or .deallocate()
  cout << masked << endl;
  i1.copyTo(masked, 1 - mask);
  cout << masked << endl;
  return 0;
}

behaves very differently when masked.release() is replaced by masked.deallocate(). In the latter case it seems that the matrix masked is not modified at all and the output masked is the sum of masked and invert masked matrices, thus equal to the original im1 matrix. What does deallocate() member method actually do? I use openCV 3.1.


Solution

  • deallocate() will deallocate the data directly form the cv::Mat. However, release() will just decrease the ref_count of the cv::Mat and if it hits 0, it will call deallcoate by itself.

    Summary: use release always until you know what you are doing.

    Be aware also that you do not need to invoke any of them. release will be invoked during the destructor of cv::Mat.

    P.S using the data of cv::Mat after deallocating is considered undefined behavior.