天天看點

cv::Mat通路元素的方法

#include "opencv2/opencv.hpp"

#include <iostream>

using namespace std;

using namespace cv;

int main(int argc,char** argv)

{

const char* filename = "google.png";

//CV_8UC3

//相應的CV_8SC3---Vec3s

//相應的CV_16UC3---Vec3w

Mat mat_CV_8UC3 = imread(filename,IMREAD_COLOR);

   for( size_t nrow = 0; nrow < mat_CV_8UC3.rows; nrow++)

    {

  for(size_t ncol = 0; ncol < mat_CV_8UC3.cols; ncol++)

  {

  Vec3i bgr = mat_CV_8UC3.at<Vec3b>(nrow,ncol);//用Vec3b也行

  cout   << "("<<bgr.val[0]<<","

  <<bgr.val[1]<<","

  <<bgr.val[2]<<")";

  }

  cout << endl;

    }

    for( size_t nrow = 0; nrow < mat_CV_8UC3.rows; nrow++)

    {

    uchar* data = mat_CV_8UC3.ptr<uchar>(nrow);

  for(size_t ncol = 0; ncol < mat_CV_8UC3.cols * mat_CV_8UC3.channels(); ncol++)

  {

cout << int( data[ncol] ) ;

  }

  cout << endl;

    }

   //------CV_8UC1----------start---

   //

Mat mat_CV_8UC1 = imread(filename,IMREAD_GRAYSCALE);

   for( size_t nrow = 0; nrow < mat_CV_8UC1.rows; nrow++)

   {

  for(size_t ncol = 0; ncol < mat_CV_8UC1.cols; ncol++)

  {

  uchar val = mat_CV_8UC1.at<uchar>(nrow,ncol);

  //

  cout << (int(val) > 200 ? 1 :0) ;//cout<<int(val)<< endl ;

  }

  cout << endl ;

   }

   cout << endl;

    for ( size_t row = 0 ; row < mat_CV_8UC1.rows ; ++row) 

    {

uchar* ptr = mat_CV_8UC1.ptr<uchar>(row);

for ( size_t col = 0 ; col < mat_CV_8UC1.cols ; ++col) 

{

cout << ( int(ptr[col]) > 200 ? 1 :0) ;//cout<<int(val)<< endl ;

}

cout << "\n" ;

}

cout << endl;

   MatIterator_<uchar> it = mat_CV_8UC1.begin<uchar>(), it_end = mat_CV_8UC1.end<uchar>();

   for(int cnt = 1; it != it_end; ++it)

    {

      cout << ( int(*it) > 200 ? 1 : 0) ;

      if( (cnt++ % mat_CV_8UC1.cols) ==0 )

      cout << endl;    

    }

   //------CV_8UC1----------end---   

  return 0;

}

原文位址:http://blog.csdn.net/moc062066/article/details/6949826