Below is some code from a C++ procedure. The original can be found here;
https://code.ros.org/trac/opencv/browser/trunk/opencv/modules/imgproc/src/grabcut.cpp
My perspective is that I am a C# rather than C++ programmer so this code is a bit of a mystery to me even though I ran it through a code converter and it came out unchanged.
My questions are: a). How does ‘coefs’ become an array, and b). how does ‘c’ get populated?
To give a bit more information: ‘coefs’ does not seem to start out as an array and ‘c’ somehow seems to magically get at least 8 items
// fields in class called MAT:
// a distance between successive rows in bytes; includes the gap if any
size_t step;
// pointer to the data
uchar* data;
// where ptr comes from:
template<typename _Tp> _Tp* ptr(int y=0);
template<typename _Tp> inline _Tp* Mat::ptr(int y)
{
CV_DbgAssert( (unsigned)y < (unsigned)rows );
return (_Tp*)(data + step*y);
}
.....
// original question code:
static const int componentsCount = 5;
Mat model;
float* coefs;
float* mean;
float* cov;
coefs = model.ptr<float>(0);
mean = coefs + componentsCount;
cov = mean + 3*componentsCount;
for( int ci = 0; ci < componentsCount; ci++ )
if( coefs[ci] > 0 )
calcInverseCovAndDeterm( ci );
void GMM::calcInverseCovAndDeterm( int ci )
{
if( coefs[ci] > 0 )
{
float *c = cov + 9*ci;
float dtrm =
covDeterms[ci] = c[0]*(c[4]*c[8]-c[5]*c[7]) - c[1]*(c[3]*c[8]-c[5]*c[6]) + c[2]*(c[3]*c[7]-c[4]*c[6]);
When you declare an array like this:
my_intsis an array. But in C++my_intscan also be evaluated as a pointer to the first item in the array. So code like this:…is legal and valid, not to mention very common. You can also use
the_first_intas if it were also an array, like this:…which makes it practically seamless to go between C-style arrays and pointers and back again.
In your code you declare a pointer to a
float:(by the way, this should be initialized to NULLL, but that’s another story), and then you set it to some value:
I don’t know what
model.ptr<float>(0)does, but it probably either allocates an array and returns a pointer to that, or returns a pointer to an array that was already set up.Now because the
coefsis a pointer tofloat, you can use it like it were an array, which you do in the loop:That’s why this works.