I’m hard working on rubyk and implementing matrix processing (again). Since I do not want to reinvent the wheel, I decided to use a matrix format compatible with the computer vision library opencv. I chose this library because of their great support for many matrix operations and the license type which is compatible with rubyk’s (MIT).

Since matrices are large objects, I need a way to share them and make sure it’s not deleted while being used. This means sharing pointers to some data and having a reference counter.

strange names

Looking in opencv code, I found a nice candidate for my matrix class: CvMat. Inside this thing, there are two fields of interest: “data” (a union of pointers) and “refcount” (a pointer to int).

I think “great, I even have a reference counter !” but then I find this inside cvDecRefData:

mat->data.ptr = NULL;
if( mat->refcount != NULL && --*mat->refcount == 0 )
    cvFree( &mat->refcount );
mat->refcount = NULL;

I think “Wow ! Why don’t they free the data ?”

In fact, the “refcount” is actually a pointer to a struct like this:

struct {
  int ref_count;
  void * data;
};

and the “data” points inside this thing.

Aiii, that’s something that should be better documented, especially when there are other places in the code with a “refcount” used in other ways. Just calling it “refcount_and_data” would be nice.

cv::Mat

Thanks to “Vadim Pisarevsky” on the mailing list who pointed me to this new implementation of a C++ oriented matrix implementation.

You can find it in “cxcore.hpp” with some code in “cxoperations.hpp”.