How to access the nth channel of Mat in opencv?
2 answers
Let's say n = 10
and we want to access the 4th
pixel channel (i, j)
. Here's a simple example:
typedef cv::Vec<uchar, 10> Vec10b;
// ....
// Create the mat
cv::Mat_<Vec10b> some_mat;
// Access 4th channel
uchar value = some_mat.at<Vec10b>(i,j)(4);
// or
uchar value = some_mat.at<Vec10b>(i,j)[4];
Hope this helps you. Note that you can omit the line typedef
, I just think it's easier.
+2
source to share
To be able to handle an arbitrary number of channels, you can use cv::Mat::ptr
some pointer arithmetic as well.
For example, a simple approach that only supports data type CV_8U
would be:
#include <opencv2/opencv.hpp>
#include <cstdint>
#include <iostream>
inline uint8_t get_value(cv::Mat const& img, int32_t row, int32_t col, int32_t channel)
{
CV_DbgAssert(channel < img.channels());
uint8_t const* pixel_ptr(img.ptr(row, col));
uint8_t const* value_ptr(pixel_ptr + channel);
return *value_ptr;
}
void test(uint32_t channel_count)
{
cv::Mat img(128, 128, CV_8UC(channel_count));
cv::randu(img, 0, 256);
for (int32_t i(0); i < img.channels(); ++i) {
std::cout << i << ":" << get_value(img, 32, 32, i) << "\n";
}
}
int main()
{
for (uint32_t i(1); i < 10; ++i) {
test(i);
}
return 0;
}
0
source to share