How to get properly typed cv::Mat_<_Tp>.data as _Tp*?

63 Views Asked by At

In my template functions I have instances of cv::Mat_<T>. My problem is that cv::Mat_<T>.data does not return T*, but uchar*.

Is it safe to cast cv::Mat_<T>.data to T* using a reinterpret_cast<T*>?

One example would be this:


template<typename T>
cv::Mat_<T> AddAxis(cv::Mat_<T> const &tensor) {
    const int kTensorOrder = tensor.size.dims();
    const int kNewTensorOrder = kTensorOrder+1;
    int new_tensor_size[kNewTensorOrder];
    new_tensor_size[0] = 1;
    for (int i = 0; i < kTensorOrder; i++) {
        new_tensor_size[i+1] = tensor.size[i];
    }
    cv::Mat_<T> new_tensor = cv::Mat_<T>(kNewTensorOrder, new_tensor_size, tensor.data);  // A
    cv::Mat_<T> new_tensor = cv::Mat_<T>(kNewTensorOrder, new_tensor_size, reinterpret_cast<T*>(tensor.data));  // B
    cv::Mat_<T> new_tensor = cv::Mat_<T>(kNewTensorOrder, new_tensor_size, const_cast<T*>(tensor.template ptr<T>(0)));  // C

    return new_tensor;
}

Line A fails compilation with the message

error: no matching function for call to 'cv::Mat_::Mat_(const int&, int [kNewTensorOrder], uchar* const&)'

Line B compiles fine, but is it safe, though, even when tensor.isContinuous() is false?

Line C also compiles fine. Should I use this one?

0

There are 0 best solutions below