使用 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;
}