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

时间:2017-10-13 21:04:32

标签: 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;

编辑:

更新了以下代码,为我编译错误无效类型'unsigned char [int]'对于数组下标

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;

    }

编译错误位于我使用[]访问通道索引的位置。我想这不是访问频道的正确方法。

1 个答案:

答案 0 :(得分:1)

使用多个渠道访问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;
}

对于单通道cv :: Mat

df %>% filter(b == !!b)

感谢https://jsfiddle.net/yeu7f3f2/