Mat的存储方式
image.at<uchar>(i,j):取出灰度图像中i行j列的点。
image.at<Vec3b>(i,j)[k]:取出彩色图像中i行j列第k通道的颜色点,k=[0,1,2],分别代表B,G,R。
uchar,Vec3b都是图像像素值的类型,在core里它是通过typedef Vec<T,N>来定义的,N代表元素的个数,T代表类型。
先随便定义一个Mat
Mat mat(3, 4, CV_8UC3, Scalar(0, 0, 1));
cout << mat << endl;
1. 通过 .at<typename>(i,j) 遍历
for (int i = 0; i < mat.rows; ++i) {
for (int j = 0; j < mat.cols; ++j) {
Vec3b vc = mat.at<Vec3b>(i, j);
cout << (int)vc.val[0] << " " << (int)vc.val[1] << " " << (int)vc.val[2] << " ";
}
cout << endl;
}
2. 通过行指针 .ptr<uchar>(k)来遍历
for (int i = 0; i < mat.rows; i ++) {
uchar *ptr = mat.ptr<uchar>(i);
for (int j = 0; j < mat.cols*mat.channels(); ++j) {
cout << (int)ptr[j] << " ";
}
cout << endl;
}
3. 通过迭代器Mat_iterator来遍历
MatIterator_<Vec3b> it = mat.begin<Vec3b>();
MatIterator_<Vec3b> end = mat.end<Vec3b>();
for (int i = 0; it != end; ++it) {
cout << (int)(*it).val[0] << " " << (int)(*it).val[1] << " " << (int)(*it).val[2];
++i;
if (i % (mat.cols * mat.channels()) != 0) {
cout << " ";
}
if ((i % mat.cols) == 0) {
cout << endl;
}
}