简体   繁体   中英

Strange behavior displaying matrix opencv

I'm trying to implement the Bayer Color Filter Array in OpenCV!

Here's the code:

#include <cv.h>
#include <highgui.h>
#include <iostream>

using namespace cv;
using std::cout;
using std::endl;

int main( int argc, char** argv )
{
  int rows = 4, cols = 4;

  cv::Mat_<uchar> mask(rows, cols);

  cv::Mat_<uchar> pattern(1, cols);

  for (int i = 0; i < cols; i = i + 2) pattern(0, i) = 1;

  for (int j = 0; j < rows; j = j + 2) pattern.row(0).copyTo(mask.row(j));

  cout << mask << endl;

  namedWindow( "Result" );
  imshow( "Result", mask );

  waitKey(0);

  return 0;
}

The problem is when I comment the lines 23 to 26, the output in the statement of the line 21 is as I expect.

[1, 0, 1, 0;
  0, 0, 0, 0;
  1, 0, 1, 0;
  0, 0, 0, 0]

but when the lines are uncommented, the output become something like that:

[1, 100, 1, 48;
  47, 117, 115, 98;
  1, 100, 1, 48;
  49, 47, 50, 45]

I don't understand what's wrong. I'm printing the values before the commented lines, but somehow it seems they are affecting the matrix from the start.

you are using uninitialized values. Without the namedWindow and imshow stuff you were just lucky.

Try:

using namespace cv;
using std::cout;
using std::endl;

int main( int argc, char** argv )
{
  int rows = 4, cols = 4;

  cv::Mat_<uchar> mask(rows, cols);

  cv::Mat_<uchar> pattern(1, cols);

  // ------------------------------------------
  // initialize your matrices:
  for(int j=0; j<rows; ++j)
      for(int i=0; i<cols; ++i)
      {
          mask(j,i) = 0;
      }
  for(int i=0; i<cols; ++i) pattern(0,i) = 0;
  // ------------------------------------------


  for (int i = 0; i < cols; i = i + 2) pattern(0, i) = 1;

  for (int j = 0; j < rows; j = j + 2) pattern.row(0).copyTo(mask.row(j));

  cout << mask << endl;

  namedWindow( "Result" );
  imshow( "Result", mask );

  waitKey(0);

  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM