在OpenCV 2.3中将值分配给Mat数组时出现问题-看起来很简单 [英] Problem assigning values to Mat array in OpenCV 2.3 - seems simple

查看:60
本文介绍了在OpenCV 2.3中将值分配给Mat数组时出现问题-看起来很简单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用针对OpenCV 2.3的新API,我在将值分配给循环内的Mat数组(或说图像)时遇到了麻烦.这是我正在使用的代码片段;

Using the new API for OpenCV 2.3, I am having trouble assigning values to a Mat array (or say image) inside a loop. Here is the code snippet which I am using;

    int paddedHeight = 256 + 2*padSize; 
    int paddedWidth = 256 + 2*padSize;  

    int n = 266; // padded height or width

    cv::Mat fx = cv::Mat(paddedHeight,paddedWidth,CV_64FC1);
    cv::Mat fy = cv::Mat(paddedHeight,paddedWidth,CV_64FC1);        
    float value = -n/2.0f;

    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
            fx.at<cv::Vec2d>(i,j) = value++;                    

        value = -n/2.0f;
    }

    meshElement = -n/2.0f;

    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
            fy.at<cv::Vec2d>(i,j) = value;
        value++;
    }

现在,在j = 133的第一个循环中,我得到了一个异常,该异常似乎与图像的深度有关,在这里我无法弄清楚我在做什么错.

Now in the first loop as soon as j = 133, I get an exception which seems to be related to depth of the image, I cant figure out what I am doing wrong here.

请告知!谢谢!

推荐答案

您正在以2分量双精度矢量(使用.at<cv::Vec2d>())访问数据,但是创建的矩阵仅包含1个分量双精度(使用).创建每个元素包含两个成分的矩阵(使用CV_64FC2),或者,似乎更适合您的代码的方式,使用.at<double>()将值作为简单的双精度值进行访问.这恰好在j = 133处爆炸,因为它是图像大小的一半,当仅包含1时被视为包含2分量向量,则宽度只有其一半.

You are accessing the data as 2-component double vector (using .at<cv::Vec2d>()), but you created the matrices to contain only 1 component doubles (using CV_64FC1). Either create the matrices to contain two components per element (with CV_64FC2) or, what seems more appropriate to your code, access the values as simple doubles, using .at<double>(). This explodes exactly at j=133 because that is half the size of your image and when treated as containing 2-component vectors when it only contains 1, it is only half as wide.

或者也许您可以将这两个矩阵合并为一个,每个元素包含两个组件,但这取决于您将来使用这些矩阵的方式.在这种情况下,您还可以将两个循环合并在一起并真正设置一个2分量向量:

Or maybe you can merge these two matrices into one, containing two components per element, but this depends on the way you are going to use these matrices in the future. In this case you can also merge the two loops together and really set a 2-component vector:

cv::Mat f = cv::Mat(paddedHeight,paddedWidth,CV_64FC2);
float yValue = -n/2.0f;

for(int i=0;i<n;i++)
{
    float xValue = -n/2.0f;

    for(int j=0;j<n;j++)
    {
        f.at<cv::Vec2d>(i,j)[0] = xValue++;
        f.at<cv::Vec2d>(i,j)[1] = yValue;
    }

    ++yValue;
}

如果对于同一元素始终需要两个值(fx的值和fy的值),则这可能会产生更好的内存访问方案.

This might produce a better memory accessing scheme if you always need both values, the one from fx and the one from fy, for the same element.

这篇关于在OpenCV 2.3中将值分配给Mat数组时出现问题-看起来很简单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆