Search code examples
c++opencvmemory-management

How to access reference count of cv::Mat


Suppose I want to track the reference count of a cv::Mat by simply printing it in an executable.

#include <iostream>
#include <opencv2/opencv>

int main()
{
    cv::Mat m;
    int refCount = (m.u)->refcount; // <--- Crashes here!
    std::cout << refCount << std::endl;
}

If I run the above code I get a runtime error:

unknown file: SEH exception with code 0xc0000005 thrown in the test body.

What am I doing wrong?

Code reference: https://github.com/opencv/opencv/blob/4.x/modules/core/include/opencv2/core/mat.hpp


Solution

  • refcount is a member of an cv::Mat::u which is the internal data holder of the cv::Mat.

    Usually you shouldn't access it.

    If you have a good reason for that, you should be aware that cv::Mat::u is allocated only if the cv::Mat refers to some data.
    In your case it is default constructed to an empty one and so cv::Mat::u is null, causing an access violation when you dereference it.

    In order to fix it you can check for null:

    int refCount = (m.u) ? ((m.u)->refcount) : 0;
    

    Note that if your cv::Mat was not empty, e.g.:

    cv::Mat m(3, 4, CV_8UC3);
    

    Your approach would have worked.


    A side note:
    #include <opencv2/opencv> should be #include <opencv2/opencv.hpp>.