1、利用 at 函数读取
(1)单通道图像读取方式
- Mat img1 = imread(filename,IMREAD_GRAYSCALE);
- for( size_t nrow = 0; nrow < img1.rows; nrow++)
- {
- for(size_t ncol = 0; ncol < img1.cols; ncol++)
- {
- uchar val = mat_CV_8UC1.at<uchar>(nrow,ncol);
- }
- }
(2) 三通道图像读取方式
- Mat img2 = imread(filename,IMREAD_COLOR);
- for( size_t nrow = 0; nrow < img2.rows; nrow++)
- {
- for(size_t ncol = 0; ncol < img2.cols; ncol++)
- {
- Vec3i bgr = mat_CV_8UC3.at<Vec3b>(nrow,ncol);//用Vec3b也行
- cout << "("<<bgr.val[0]<<","
- <<bgr.val[1]<<","
- <<bgr.val[2]<<")";
- }
- cout << endl;
- }
2、使用指针读取
- for( size_t nrow = 0; nrow < img3.rows; nrow++)
- {
- uchar* data = img3.ptr<uchar>(nrow);
- for(size_t ncol = 0; ncol < img3.cols * img3.channels(); ncol++)
- {
- cout << int( data[ncol] ) ;
- }
- cout << endl;
- }
3、使用迭代器
- Mat img4 = imread(filename,IMREAD_GRAYSCALE);
- MatIterator_<uchar> it = img4.begin<uchar>(), it_end = img4.end<uchar>();
- for(int cnt = 1; it != it_end; ++it)
- {
- cout << ( int(*it) ) ;
- if( (cnt++ % img4.cols) ==0 )
- cout << endl;
- }
4、使用矩阵元素的地址定位知识
- Mat img5(rows, cols,CV_8U, Scalar(0));
- for( size_t nrow = 0; nrow < img5.rows; nrow++)
- for(size_t ncol = 0; ncol < img5.cols; ncol++)
- {
- cout<<(int)(*(img5.data+img5.step[0]*nrow+img5.step[1]*ncol));
- }
5、补充:在使用 at 函数的情况下需要预先知道Mat变量中存储的元素类型,如果类型不匹配就会出现读错误。所以可以采用c++ boost库中的BOOST_TYPEOF来获取图像的元素数据类型。
例:
-
- Mat img6 = imread(filename);
- typedef BOOST_TYPEOF(*img6.data) ElementType
- for( size_t nrow = 0; nrow < img1.rows; nrow++)
- {
- for(size_t ncol = 0; ncol < img1.cols; ncol++)
- {
- cout<<mat_CV_8UC1.at<ElementType>(nrow,ncol);
- }
- }