takfuruya
takfuruya

Reputation: 2561

Different ways to initialize matrix and access its data

I'm reading code and found:

Mat L(3, 3, DataType<double>::type);
double *pL = L.ptr<double>(0);

But I am used to doing

Mat L(3, 3, CV_64F);
double* pL = static_cast<double*>(L.data);

Which is better? Are they the same?

Upvotes: 1

Views: 58

Answers (2)

Michael Burdinov
Michael Burdinov

Reputation: 4448

.ptr() approach come to replace .data approach. The result of both is the same (after fixing bug mentioned by @herohuyongtao), but .ptr() approach is somewhat better.

1) C++ gives you a LOT of freedom to do practically everything. Casting is part of this freedom. But it has a price: work is done during run time instead of compilation time. And it is good in hiding bugs from compiler. For this reason it is highly recommended not to use casting unless there no other way around it.

2) Using L.ptr< double>(i) will give you pointer to row 'i', unlike L.data that can only give you pointer to first row. This saves you calculation of step between following rows, which was a source of very frequent bugs.

Upvotes: 2

herohuyongtao
herohuyongtao

Reputation: 50717

The second version will fail while compiling. L.data is a uchar *, which cannot be static casted to double *. I guess you are meaning reinterpret_cast here. Check out When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?.

Mat L(3, 3, CV_64F);
double* pL = reinterpret_cast<double*>(L.data); 

Under this sense, it will have the same effect with the first version, i.e. pointer double *pL points to the data of Mat L. Just use the one you are more familiar with.

Upvotes: 2

Related Questions