参考:http://www.cnblogs.com/ronny/p/opencv_road_2.html
http://blog.csdn.net/xiaowei_cqu/article/details/7771760
http://segmentfault.com/a/1190000000598650
本文主要是在opencv2.0以后的版本,使用Mat作为数据的基本操作类型。
最快的方法-----使用指针遍历图像
1 遍历单通道图像
利用指针访问
Mat src = imread("lena.jpg", 0);
Mat dst = Mat(src.rows, src.cols, CV8U_C1);
for (int i = 0; i < row; ++i) { uchar *srcptr = src.ptr<uchar>(i); uchar *dstptr = dst.ptr<float>(i); for (int j = 0; j < col; ++j) { *(dstptr + j) = *(srcptr + j); } }
利用at访问
cv::Mat srcgrayimg; cv::cvtColor(srcimg, srcgrayimg, CV_BGR2GRAY); for (int y = facetybegin; y < facetyend; ++y) { for (int x = facetybegin; x < facetyend; ++x) { FacePoint dstpoint; dstpoint.x = x; dstpoint.y = y; if (isPointInRect(dstpoint, quadrilateralLeft) == true) { sumLeft += srcgrayimg.at<uchar>(y, x); areaLeft++; } if (isPointInRect(dstpoint, quadrilateralRight) == true) { sumRight += srcgrayimg.at<uchar>(y, x); areaRight++; } } }
2 遍历彩色图像
这里可以通过两种方式Vec3b和step elemSize两种方式来访问
Mat src = imread("lena.jpg", 1); //通过指针遍历彩色图像 uchar *data = src.data; int i = 100; int j = 100;
//获取第i行 第j列的元素RGB值
//获取B通道 int pix1 = src.at<Vec3b>(i, j)[0]; int pix2 = *(data + i * src.step + j* src.elemSize()+0); cout << pix1 << " " << pix2 << endl; cout << src.step << " " << src.elemSize() << endl;
通过指针,适合与任何通道的图像
channel = 3 int row = src.rows; int col = src.cols; Mat dst = Mat(row, col, CV_16UC3); for (int i = 0; i < row; ++i) { ushort *dataWarpRow = dst.ptr<ushort>(i); for (int j = 0; j < col; ++j) { ushort *dataWarpCol = dataWarpRow + j * src.channels(); if ((dataWarpCol)[0] == 0 && (dataWarpCol)[1] == 0 && (dataWarpCol)[2] == 0) { ; } } }