2

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.

4

2 回答 2

3

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.

于 2016-07-12T12:02:13.400 回答
1

While Mat::deallocate() deallocates the matrix, Mat::release() decreases the reference counter and deallocates the matrix if needed. When using release() if reference count reaches 0, Mat is then deallocated, while deallocate() deallocates it always. More information HERE

于 2016-07-12T12:05:01.747 回答