OpenCV中Mat数据读取方法
- 使用指向Mat数据部分的指针
- 使用迭代器
- 使用at方法或者Mat_类型
1、使用指向Mat数据部分的指针
1 Mat& ScanImageAndReduceC(Mat& I, const uchar* const table)
2 {
3 // accept only char type matrices
4 CV_Assert(I.depth() != sizeof(uchar));
5
6 int channels = I.channels();
7
8 int nRows = I.rows;
9 int nCols = I.cols * channels;
10
11 if (I.isContinuous())
12 {
13 nCols *= nRows;
14 nRows = 1;
15 }
16
17 int i,j;
18 uchar* p;
19 for( i = 0; i < nRows; ++i)
20 {
21 p = I.ptr<uchar>(i);
22 for ( j = 0; j < nCols; ++j)
23 {
24 p[j] = table[p[j]];
25 }
26 }
27 return I;
28 }
2、使用迭代器
1 Mat& ScanImageAndReduceIterator(Mat& I, const uchar* const table)
2 {
3 // accept only char type matrices
4 CV_Assert(I.depth() != sizeof(uchar));
5
6 const int channels = I.channels();
7 switch(channels)
8 {
9 case 1:
10 {
11 MatIterator_<uchar> it, end;
12 for( it = I.begin<uchar>(), end = I.end<uchar>(); it != end; ++it)
13 *it = table[*it];
14 break;
15 }
16 case 3:
17 {
18 MatIterator_<Vec3b> it, end;
19 for( it = I.begin<Vec3b>(), end = I.end<Vec3b>(); it != end; ++it)
20 {
21 (*it)[0] = table[(*it)[0]];
22 (*it)[1] = table[(*it)[1]];
23 (*it)[2] = table[(*it)[2]];
24 }
25 }
26 }
27
28 return I;
29 }
3、使用at方法或者Mat_类型
1 Mat& ScanImageAndReduceRandomAccess(Mat& I, const uchar* const table)
2 {
3 // accept only char type matrices
4 CV_Assert(I.depth() != sizeof(uchar));
5
6 const int channels = I.channels();
7 switch(channels)
8 {
9 case 1:
10 {
11 for( int i = 0; i < I.rows; ++i)
12 for( int j = 0; j < I.cols; ++j )
13 I.at<uchar>(i,j) = table[I.at<uchar>(i,j)];
14 break;
15 }
16 case 3:
17 {
18 Mat_<Vec3b> _I = I;
19
20 for( int i = 0; i < I.rows; ++i)
21 for( int j = 0; j < I.cols; ++j )
22 {
23 _I(i,j)[0] = table[_I(i,j)[0]];
24 _I(i,j)[1] = table[_I(i,j)[1]];
25 _I(i,j)[2] = table[_I(i,j)[2]];
26 }
27 I = _I;
28 break;
29 }
30 }
31
32 return I;
33 }