Note that InputArray::getObj()
returns the object by whom it was created. So casting only works, if _input
was created using a std::vector
! This can be checked via InputArray::isVector()
.
Otherwise, a new std::vector
object must be created. Unfortunately, there is no way to tell std::vector
to use existing data. I think it is not even possible when using your own allocator. If you still want a std::vector
, use pointers/iterators (either in constructor or in std::vector::assign()
) to create a new object with a copy of the data. You can obtain the size directly from _input
via InputArray::total()
.
Vector
Based on the previous observations, I combined the attempts proposed by Poly.
std::vector<Point2f> *input;
if (_input.isVector()) {
input = static_cast<std::vector<Point2f>*>(_input.getObj());
} else {
size_t length = _input.total();
Point2f* data = reinterpret_cast<Point2f*>(_input.getMat().data);
input = new std::vector<Point2f>(data, data + length);
}
Template
To reuse code for other types, I recommend using templates.
template<class T>
std::vector<T>& getVec(InputArray _input) {
std::vector<T> *input;
if (_input.isVector()) {
input = static_cast<std::vector<T>*>(_input.getObj());
} else {
size_t length = _input.total();
T* data = reinterpret_cast<T*>(_input.getMat().data);
input = new std::vector<T>(data, data + length);
}
return *input;
}
Further, you should check if types are compatible via InputArray::type()
.
Arrays
If you just want easy indexing, you could of course use standard C-style arrays (Note that C++-style std::array
also needs to copy data).
Point2f* data = reinterpret_cast<Point2f*>(_input.getMat().data);
Then you can access data via
Point2f p = data[5];