c++ - OpenCV cv::Mat 'ones' 用于多 channel 矩阵?

标签 c++ image image-processing opencv matrix

在 OpenCV 中使用单 channel (例如 CV_8UC1)Mat 对象时,这会创建一个全部为 Mat 的对象:cv::Mat img = cv::Mat::ones( x,y,CV_8UC1).

但是,当我使用 3 channel 图像(例如 CV_8UC3)时,事情变得有点复杂。执行 cv::Mat img = cv::Mat::ones(x,y,CV_8UC3)ones 放入 channel 0,但 channel 1 和 2 包含 那么,如何将 cv::Mat::ones() 用于多 channel 图像?

下面是一些代码,可以帮助您理解我的意思:

void testOnes() {
 int x=2; int y=2; //arbitrary

 // 1 channel
 cv::Mat img_C1 = cv::Mat::ones(x,y,CV_8UC1);
 uchar px1 = img_C1.at<uchar>(0,0); //not sure of correct data type for px in 1-channel img
 printf("px of 1-channel img: %d \n", (int)px1); //prints 1

 // 3 channels
 cv::Mat img_C3 = cv::Mat::ones(x,y,CV_8UC3); //note 8UC3 instead of 8UC1
 cv::Vec3b px3 = img_C3.at<cv::Vec3b>(0,0);
 printf("px of 3-channel img: %d %d %d \n", (int)px3[0], (int)px3[1], (int)px3[2]); //prints 1 0 0
}

所以,我希望看到这个打印输出:px of 3-channel img: 1 1 1,但我看到的是:px of 3-channel img: 1 0 0

附言在发布之前我做了很多搜索。我无法通过在 SO 中搜索“[opencv] Mat::ones”或“[opencv] +mat +ones”来解决此问题。

最佳答案

我不使用 OpenCV,但我相信我知道这里发生了什么。您定义了一个数据类型,但您为此请求值“1”。 Mat 类似乎没有注意到您拥有多 channel 数据类型这一事实,因此它只是将“1”转换为 3 字节无符号字符。

所以不要使用 ones 函数,只需使用标量构造函数:

cv::Mat img_C3( x, y, CV_8UC3, CV_RGB(1,1,1) );

关于c++ - OpenCV cv::Mat 'ones' 用于多 channel 矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12343662/

相关文章:

c++ - 没有卡尔曼滤波器的 BackgroundSubtractorGMG?

c++ - C++模板参数有什么要求?

python - 在 tkinter 中查看的枕头生成图像中的颜色与保存文件中的颜色不匹配

php - 在 php 中从中心自动裁剪 Tumble 的照片

java - 在 imageView 中调用图像破坏生成的图像

c++ - 关于如何在 Visual C++ 中将字节数组缓冲区复制到字节指针的问题

c++ - 关于使用读写在文件中存储结构

php - 如何在wordpress中获取img标签的图片url

javascript - 如何选择FileReader的读取方式?

image - 立方到等角投影算法