c++ - 如何访问 3D CV::Mat 的索引

标签 c++ opencv

我在尝试访问 3D CV::Mat 的索引时遇到段错误。代码如下,

int channel = 3;
int sizes[] = { imageheight, imageWidth};
CV::Mat test(2, sizes, CV_8UC3)
for(int i=0;i<image2D->size();i++)
    {
        Point2D &_point = image2D->at(i);       

        test.at<unsigned char>(_point.y,_point.x,0) = _point.rgb.r;
        test.at<unsigned char>(_point.y,_point.x,1) = _point.rgb.g;
        test.at<unsigned char>(_point.y,_point.x,2) = _point.rgb.b; // Segmentation fault in this line
    }

以下方式不会崩溃,但会输出黑色图像。我不确定我做的是否正确,

unsigned char *ptest = test.ptr<unsigned char>(_point.y);
        ptest[channel*_point.x+ 0] = _point.rgb.r;
        ptest[channel*_point.x+ 1] = _point.rgb.g;
        ptest[channel*_point.x+ 2] = _point.rgb.b;

编辑:

将代码更新为以下代码会出现编译错误invalid types ‘unsigned char[int]’ for array subscript

Matrix test(imageheight, imageWidth, CV_8UC3);
for(int i=0;i<image2D->size();i++)
    {
        Point2D &_point = image2D->at(i);
        // Compile error on the below 3 lines.
        test.at<unsigned char>(_point.y, _point.x)[0] = _point.rgb.b;
        test.at<unsigned char>(_point.y, _point.x)[1] = _point.rgb.g;
        test.at<unsigned char>(_point.y, _point.x)[2] = _point.rgb.r;

    }

编译错误在我用[]访问 channel 索引的位置。我想这不是访问 channel 的正确方式。

最佳答案

使用多个 channel 访问 cv::Mat 的最简单方法,

cv::Mat3b test(imageheight, imageWidth, CV_8UC3);
for(int i=0;i<image2D->size();i++)
{
    Point2D &_point = image2D->at(i);
    test.at<cv::Vec3b>(_point.y, _point.x)[0] = _point.rgb.b;
    test.at<cv::Vec3b>(_point.y, _point.x)[1] = _point.rgb.g;
    test.at<cv::Vec3b>(_point.y, _point.x)[2] = _point.rgb.r;
}

对于单 channel cv::Mat

cv::Mat test(imageheight, imageWidth, CV_32FC1);

for(int i=0;i<image2D->size();i++)
{
    Point2D &_point = image2D->at(i);
    test.at<float>(_point.y, _point.x) = _point.r;
}

多亏了这个answer .

关于c++ - 如何访问 3D CV::Mat 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46738031/

相关文章:

c++ - 跟进 C++ 中的类型强制,因为它可以通过类型转换来解释

c# - 为 C# 包装 C++ CLI 类

c++ - 为什么此线程池死锁或运行太多次?

OpenCV正样本尺寸?

python - 在python中使用cmap对单 channel png进行imread时如何抑制重新缩放?

python - 从视频中提取帧到特定文件夹

opencv - BackgroundSubtractorMOG2 阴影检测在阳光充足的场景中不起作用

java - 启动程序

c++ - 程序收到信号 SIGSEGV,段错误。 C++ 列表

android - 使用 android.hardware.camera2 设置自定义分辨率和帧率