GPPK
GPPK

Reputation: 6666

How to get a value from CV_8UC4 matrix

I successfully create and fill a matrix with depth and RGB data from the Kinect V2 libfreenect2 library like so:

cv::Mat(registered.height, registered.width, CV_8UC4, registered.data).copyTo(cpu_depth);
cv::imshow("depth", cpu_depth);

I believe this matrix is equivilent to [X,Y,Z,R,G,B,A] for each point within the image. How do I access the unsigned char values within the matrix?

I have tried like this:

uchar xValue = cpu_depth.at(cv::Point(20, 20))[0];

but it doesn't compile and I feel I am missing something very obvious.

Upvotes: 3

Views: 2327

Answers (2)

avtomaton
avtomaton

Reputation: 4874

This matrix is NOT equivalent to [X,Y,Z,R,G,B,A] for each point. This matrix is 2-dimensional array of cv::Vec4b elements (i. e. cv::Vec<uchar, 4> elements - one uchar element per channel). Each element can be (R, G, B, A) or (x, y, z, val) or something else - it's just 4 values at position (x, y).

Thus for access element in position (x, y) for desired channel you can use the following options:

  • cpu_depth.at<cv::Vec4b>(cv::Point(x, y))[channel] - get channel value at point (x, y);
  • cpu_depth.at<cv::Vec4b>(y, x)[channel] - get channel value at point (x, y) - matrix first index is row, that's why firstly y and then x;
  • *(cpu_depth.ptr<uchar>(y) + 4 * x + channel) - value of pointer in y-th row and x-th column, i. e. at position (x, y).

Upvotes: 1

GPPK
GPPK

Reputation: 6666

I figured it out. You need to state that you have 4 bytes per chanel with a cast. So to correctly access points within the matrix you do this:

uchar xValue = cpu_depth.at<cv::Vec4b>(cv::Point(20, 20))[0];

Upvotes: 1

Related Questions