Ask Your Question
0

widthStep in C++ API

asked 2019-06-17 15:23:44 -0500

danfur gravatar image

Hi I had some legacy code in OpenCV C API that I want to port to C++.

In the code I have some wavelet coefficients computed into a vector: vector<vector<double>> detail This is done without OpenCv but I late ron want to use OpenCV to display and process results further.

I there store the vector detail into C API opencv Image dvImg = cvCreateImage( imgSz, 16, 1 ); and I do this using widthStep:

((ushort*)(dvImg->imageData + dvImg->widthStep*i))[j] = (short) (detail[i][j]);

Specifically it is a for loop that looks like this:

    int J = 6; //number of detail coefficients on the image
    vector<vector<double>>  detail(1*rowW, vector<double>(J * colW)); //detail coefficients
    cv::Size imgSz; // size of output image
    //the output dimensions I wish to store detail coefficients to.
    imgSz.width = J*colW;
    imgSz.height = 1*rowW;
   //the OpenCV 16-bit monochrome image Im storing to
    dvImg = cvCreateImage( imgSz, 16, 1 );

    //loop through the image
    for (int i = 0; i < imgSz.height; i++ ) {
        for (int j = 0; j < imgSz.width; j++ ){
          if ( detail[i][j] <= 0.0){
            //make sure no negative values
            detail[i][j] = 0.0;
          }
           //assign to opencv image
          ((ushort*)(dvImg->imageData + dvImg->widthStep*i))[j] = (short) (detail[i][j]);
        }
      }

Naively I thought I could simply replace this to cv::Mat for C++ API like this:

cv::Mat dvImg( imgSz, CV_16U);

And instead of:

((ushort*)(dvImg->imageData + dvImg->widthStep*i))[j] = (short) (detail[i][j]);

I would do:

dvImg.at<ushort>(j,i) = (short) (detail[i][j]);

But this doesnt seem to work, output is all scrambled, there are some particulars of how widthStep works that I seem to miss.

Helpful for any input.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2019-06-17 15:43:02 -0500

LBerger gravatar image

you can try :

    vector<vector<double>> x = { {1.7,2.8,3.9},{4,5.1,6.2} };
    Mat w(x[0]),a;
    for (int i = 1; i < x.size(); i++)
        w.push_back(Mat(x[i]));
    w = w.reshape(x[0].size());
    w.convertTo(a, CV_16U);
    cout << w << "\n";
    cout << a << "\n";

results :

[1.7, 2.8, 3.9;
 4, 5.1, 6.2]
[2, 3, 4;
 4, 5, 6]
edit flag offensive delete link more

Comments

Thanks you so much! That did it. This saved my day. ๐Ÿ™

danfur gravatar imagedanfur ( 2019-06-17 18:45:51 -0500 )edit
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2019-06-17 15:23:44 -0500

Seen: 23 times

Last updated: Jun 17