【问题标题】:How to access indexes of a 3D CV::Mat如何访问 3D CV::Mat 的索引
【发布时间】:2018-03-26 01:39:26
【问题描述】:

我在尝试访问 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;

    }

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

【问题讨论】:

  • 矩阵构造函数的第一个参数应该是通道数,应该是 3 而不是 2。另外你可能应该使用 Mat 类,而不是 Matrix。
  • 我已经编辑了这个问题。矩阵是 cv::Mat 的 typedef。我认为第一个参数是 sizes 数组的大小?
  • 检查docs。第一个参数应该是维数。编辑:刚刚意识到我在第一条评论中说的是频道数,意思是维度。因此,您的尺寸数组还应包含第三个暗淡的通道数。

标签: c++ opencv


【解决方案1】:

通过多个通道访问 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;
}

对于单通道 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

【讨论】:

    猜你喜欢
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2012-11-12
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    相关资源
    最近更新 更多