如何在 opencv 中访问 Mat 的第 n 个通道?
how to access nth channel of a Mat in opencv?
我知道如何使用 Vec3b
访问三个频道 cv::Mat
。但是现在我有一个 n
通道 cv::Mat
并且 n
不是常量(使用 cv::Vec<uchar, n>
)。我现在如何访问 cv::Mat
个频道?
假设 n = 10
,我们想要访问像素 (i, j)
的 4th
通道。这是一个简单的例子:
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];
希望对您有所帮助。请注意,您可以省略 typedef
行,我只是认为这样更容易。
为了能够处理任意数量的通道,您可以使用 cv::Mat::ptr
和一些指针算法。
例如,仅支持 CV_8U
数据类型的简单方法如下:
#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;
}
我知道如何使用 Vec3b
访问三个频道 cv::Mat
。但是现在我有一个 n
通道 cv::Mat
并且 n
不是常量(使用 cv::Vec<uchar, n>
)。我现在如何访问 cv::Mat
个频道?
假设 n = 10
,我们想要访问像素 (i, j)
的 4th
通道。这是一个简单的例子:
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];
希望对您有所帮助。请注意,您可以省略 typedef
行,我只是认为这样更容易。
为了能够处理任意数量的通道,您可以使用 cv::Mat::ptr
和一些指针算法。
例如,仅支持 CV_8U
数据类型的简单方法如下:
#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;
}