Sirine Bouslama
Sirine Bouslama

Reputation: 11

resize matrix with copying the data opencv

I am trying to create a matrix with only one column from another matrix and of course with copying the data.

void redim( Mat in , Mat &out) {

  for (int l=0 ; l < in.rows*in.cols ; l++){
    for(int j=0; j< in.rows ; j++){
        for(int i=0 ; i < in.cols; i++){
        out.at <float> (l,0)= in.at <float> (j,i); 
        }
     }  
   }
}
int main(){
Mat It3;
It3 = (Mat_<double>(2,3) << 0,4,6,7,8,9);
Mat S= Mat :: zeros ( It3.rows* It3.cols , 1, CV_32FC1) ; 
redim(It3,S);
waitKey();
}

But I got as result the matrix S=[0;0;0;0;0;0].

Upvotes: 1

Views: 441

Answers (1)

Miki
Miki

Reputation: 41765

  1. Your are mixing float and double as data type. Choose one!
  2. Your for loops don't make any sense.

You can:

  • correct your for loop, as in toSingleColumn1
  • using a for loop, but using indices, as in toSingleColumn2
  • using cv::reshape, which does exactly this, as in toSingleColumn3

See the code below. b1, b2 and b3 will be equal:

#include <opencv2\opencv.hpp>
using namespace cv;

// Use two for loops, with coordinates
void toSingleColumn1(const Mat1f& src, Mat1f& dst)
{
    int N = src.rows * src.cols;
    dst = Mat1f(N, 1);
    int i=0;
    for (int r = 0; r < src.rows; ++r) {
        for (int c = 0; c < src.cols; ++c) {
            dst(i++, 0) = src(r, c);
        }
    }
}

// Use a single for loop, with indices
void toSingleColumn2(const Mat1f& src, Mat1f& dst)
{
    int N = src.rows * src.cols;
    dst = Mat1f(N, 1);

    for (int i = 0; i < N; ++i) {
        dst(i) = src(i);
    }
}

// Use cv::reshape
void toSingleColumn3(const Mat& src, Mat& dst)
{
    // The 'clone()' is needed to deep copy the data
    dst = src.reshape(src.channels(), src.rows*src.cols).clone(); 
}

int main() 
{
    Mat1f a = (Mat1f(2,3) << 0.f, 4.f, 6.f, 7.f, 8.f, 9.f);

    Mat1f b1, b2, b3;
    toSingleColumn1(a, b1);
    toSingleColumn2(a, b2);
    toSingleColumn3(a, b3);

    return 0;
}

Upvotes: 1

Related Questions