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

隐身守侯 提交于 2019-12-23 10:37:13

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/7298734/problem-assigning-values-to-mat-array-in-opencv-2-3-seems-simple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!