使用 cvMatptrT 指针进行高效的像素访问
如果效率很重要,那么迭代 cv::Mat 对象中的像素的快速方法是使用其 ptr<T>(int r) 方法来获得指向行 r(从 0 开始的索引)的开头的指针。
根据矩阵类型,指针将具有不同的模板。
- 对于 CV_8UC1:uchar* ptr = image.ptr<uchar>(r);
- 对于 CV_8UC3:cv::Vec3b* ptr = image.ptr<cv::Vec3b>(r);
- 对于 CV_32FC1:float* ptr = image.ptr<float>(r);
- 对于 CV_32FC3:cv::Vec3f* ptr = image.ptr<cv::Vec3f>(r);
然后,通过调用 ptr[c],可以使用此 ptr 对象访问行 r 和列 c 上的像素值。
为了说明这一点,这里有一个例子,我们从磁盘加载图像并反转其蓝色和红色通道,逐个像素地操作:
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
int main(int argc, char** argv) {
    cv::Mat image = cv::imread("image.jpg", CV_LOAD_IMAGE_COLOR);
    if(!image.data) {
        std::cout << "Error: the image wasn't correctly loaded." << std::endl;
        return -1;
    }
    // We iterate over all pixels of the image
    for(int r = 0; r < image.rows; r++) {
        // We obtain a pointer to the beginning of row r
        cv::Vec3b* ptr = image.ptr<cv::Vec3b>(r);
        for(int c = 0; c < image.cols; c++) {
            // We invert the blue and red values of the pixel
            ptr[c] = cv::Vec3b(ptr[c][2], ptr[c][1], ptr[c][0]);
        }
    }
    cv::imshow("Inverted Image", image);
    cv::waitKey();
    return 0;
}