开发者

Problem assigning values to Mat array in OpenCV 2.3 - seems simple

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++;
    }

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.

Please Advise! Thanks!

Problem assigning values to Mat array in OpenCV 2.3 - seems simple


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.

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;
}

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜