OpenCV遍历图像像素是很常见的事情,比较下面的三种遍历方式哪个是最高效的。
前言
在OpenCV C++中Mat对象的内存管理由OpenCV框架自动负责内存分配与回收,基于智能指针实现内存管理。Mat对象的数据组织形式与像素块数据的存储方式,Mat对象由两个部分组成,元数据头部加像素数据块部分,图示如下:
三种图像遍历方式
方法一
基于Mat对象的随机像素访问API实现,通过行列索引方式遍历每个像素值
void method_1(Mat &image) {
double t1 = getTickCount();
int w = image.cols;
int h = image.rows;
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
Vec3b bgr = image.at<Vec3b>(row, col);
bgr[0] = 255 - bgr[0];
bgr[1] = 255 - bgr[1];
bgr[2] = 255 - bgr[2];
image.at<Vec3b>(row, col) = bgr;
}
}
double t2 = getTickCount();
double t = ((t2 - t1) / getTickFrequency()) * 1000;
ostringstream ss;
ss << "Execute time : " << std::fixed << std::setprecision(2) << t << " ms ";
putText(image, ss.str(), Point(20, 20), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0, 0, 255), 2, 8);
imshow("result", image);
}
方法二
基于Mat对象的行随机访问指针方式实现对每个像素的遍历
void method_2(Mat &image) {
double t1 = getTickCount();
int w = image.cols;
int h = image.rows;
for (int row = 0; row < h; row++) {
Vec3b* curr = image.ptr<Vec3b>(row);
for (int col = 0; col < w; col++) {
Vec3b bgr = curr[col];
bgr[0] = 255 - bgr[0];
bgr[1] = 255 - bgr[1];
bgr[2] = 255 - bgr[2];
}
}
double t2 = getTickCount();
double t = ((t2 - t1) / getTickFrequency()) * 1000;
ostringstream ss;
ss << "Execute time : " << std::fixed << std::setprecision(2) << t << " ms ";
putText(image, ss.str(), Point(20, 20), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0, 0, 255), 2, 8);
imshow("result", image);
}
除了上述的行指针遍历方式,常见的行指针还有如下:
CV_8UC1: 灰度图像
uchar* ptr = image.ptr<uchar>(row_index);
CV_8UC3: 彩色图像
Vec3b* ptr = image.ptr<cv::Vec3b>(row_index);
CV_32FC1: 单通道浮点数图像
float* ptr = image.ptr<float>(row_index);
CV_32FC3: 三通道浮点数图像
Vec3f* ptr = image.ptr<cv::Vec3f>(row_index);
方法三
直接获取Mat对象的像素块的数据指针,基于指针操作,实现快速像素方法
void method_3(Mat &image) {
double t1 = getTickCount();
int w = image.cols;
int h = image.rows;
for (int row = 0; row < h; row++) {
uchar* uc_pixel = image.data + row*image.step;
for (int col = 0; col < w; col++) {
uc_pixel[0] = 255 - uc_pixel[0];
uc_pixel[1] = 255 - uc_pixel[1];
uc_pixel[2] = 255 - uc_pixel[2];
uc_pixel += 3;
}
}
double t2 = getTickCount();
double t = ((t2 - t1) / getTickFrequency()) * 1000;
ostringstream ss;
ss << "Execute time : " << std::fixed << std::setprecision(2) << t << " ms ";
putText(image, ss.str(), Point(20, 20), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0, 0, 255), 2, 8);
imshow("result", image);
}
实践证明,唯一正确的选择是直接方法三使用data指针直接访问,但是这个在OpenCV官方的教程都没有明确说明,官方教程代码都是基于第一种方式,是为了理解与入门,这个也导致一些人在做开发的时候直接使用第一种方式做遍历,然后就是代码运行太慢,以后请用正确方式打开Mat对象遍历。