1--Mat对象的ptr模板遍历
①代码:
Mat mat(600, 800, CV_8UC3); // (H W Type)
for (int row = 0; row < mat.rows; row++){
for (int col = 0; col < mat.cols; col++){
Vec3b *c = mat.ptr<Vec3b>(row, col);
// 填充绿色
c->val[0] = 0; // B
c->val[1] = 255; // G
c->val[2] = 0; // R
}
}
②知识点1:调用ptr模板函数mat.ptr<Vec3b>(row, col);
模板函数的用法:
template<typename T>
// 函数声明或者定义
// template声明创建模板
// typename表示其后面的符号是一种数据类型,可以用class代替
// T是通用的数据类型,名称可以替换,通常为大写字母
// 定义一个模板交换函数
void mySwap(T &a, T &b)
{
T temp = a;
a = b;
b = temp;
}
// 调用
mySwap(a, b); // 隐式实例化 自动类型推导
mySwap<double>(c, d); // 显式实例化
模板函数的作用:模板函数的介绍与使用
③知识点2:Vec3b表示有3个uchar类型元素的向量,类似地还有Vec3s表示3个short int类型元素的向量。
2--Mat对象的at接口遍历
①代码:
Mat mat(600, 800, CV_8UC3); // (H W Type)
for (int row = 0; row < mat.rows; row++){
for (int col = 0; col < mat.cols; col++){
Vec3b &m = mat.at<Vec3b>(row, col);
// 填充灰色
m[0] = 100; // B
m[1] = 100; // G
m[2] = 100; // R
}
}
3--Mat对象的迭代器遍历
Mat mat(600, 800, CV_8UC3); // (H W Type)
auto it = mat.begin<Vec3b>();
auto it_end = mat.end<Vec3b>();
for(; it != it_end; ++it){
// 填充绿色
(*it).val[0] = 0; // B
(*it).val[1] = 255; // G
(*it).val[2] = 0; // R
}