1

codes 1

template<typename T>
inline T* get_pointer(cv::Mat &src, int row)
{
    return src.ptr<T>(row);
}

template<typename T>
inline T* get_pointer(cv::Mat &src, int row, int col)
{
    return get_pointer<T>(src, row) + col * src.channels();
}

template<typename T>
inline T* get_pointer(cv::Mat &src, int row, int col, int channel)
{
    return get_pointer<T>(src, row, col) + channel;
}

codes 2

cv::Mat input = //....
auto *input_ptr = get_pointer<float>(input, row, col);
//back to previous row
input_ptr = reinterpret_cast<float*>(reinterpret_cast<uchar*>(input_ptr) - input.steps);

Are they safe?

3
  • 1) reinterpret_cast<> is never "safe." (2) The pointer math in get_pointer(src, row) will fail for non-byte pixel types. (3) Are you aware of cv::Mat.ptr() methods? I think they do what you're trying to do Commented Mar 29, 2013 at 21:45
  • About the non byte pixel types, do you mean some channels like 5-6-5(3 channels with 16bits, looks like pretty command on embedded device).I always afraid of type casting on c++, especially the reinterpret cast, but I don't know other solution can go back to the previous row if I want to do it by pointer arithmetic.Thanks for your information of .ptr<T>(), I change the implementation already. Commented Mar 30, 2013 at 2:11
  • 5-6-5, or 16-bit unsigned, or float. The pointer math needs to apply the reinterpret_cast<> to the data before being used in a calculation. I think you should not implement your own templates and simply use the cv::Mat methods directly. Not sure how OpenCV handles 5-6-5, tho. Commented Apr 1, 2013 at 18:08

1 Answer 1

1

Why don't you use this (shorter and safer) code instead?

T *ptr_to_elem = &src.at<T>(row,col)[channel];

This works for non-contiguous arrays too. No potentially dangerous reinterpret_cast<> needed. The only condition for safety here is that you know the datatype T. A more safe version is when you use cv::Mat_<T> instead of cv::Mat, so that mistakes are caught at compile time instead of crashing your program at run time.

T *ptr_to_elem = &src(row,col)[channel];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.