访问图像像素

at方法

  • 基于Mat对象的随机像素访问API实现,通过行列索引方式遍历每个像素值
void method_1(Mat & img)
{
    int h = img.cols;
    int w = img.rows;
    for (int row = 0; row < w; row++)
    {
        for (int col = 0; col < h; col++)
        {
            Vec3b bgr = img.at<Vec3b>(row, col);
            img.at<Vec3b>(row, col)[0] = 255 - bgr[0];
            img.at<Vec3b>(row, col)[1] = 255 - bgr[1];
            img.at<Vec3b>(row, col)[2] = 255 - bgr[2];
        }
    }
}

指针ptr

  • 基于Mat对象的行随机访问指针方式实现对每个像素的遍历
void method_2(Mat & img)
{
    int h = img.cols;
    int w = img.rows;
    int dims = img.channels();
    for (int row = 0; row < w; row++)
    {
        uchar * ptr = img.ptr<uchar>(row);
        for (int col = 0; col < h * dims; col++)
        {
            int pv = ptr[col];
            ptr[col] = 255 - pv;
        }
    }
}

data指针

  • 直接获取Mat对象的像素块的数据指针
void method_4(Mat & img)
{
    int h = img.cols;
    int w = img.rows;
    for (int row = 0; row < w; row++)
    {
        uchar * uc_pixel = img.data + row * img.step;
        for (int col = 0; col < h; col++)
        {
            uc_pixel[0] = 255 - int(uc_pixel[0]);
            uc_pixel[1] = 255 - int(uc_pixel[1]);
            uc_pixel[2] = 255 - int(uc_pixel[2]);
            uc_pixel += 3;
        }
    }
}

迭代器

  • Mat类变量同时也是一个容器变量,因此,Mat类变量拥有迭代器,用于访问Mat类变量中的数据,通过迭代器可以实现对矩阵中每一个元素的遍历
void method_3(Mat & img)
{
    Mat_<Vec3b>::iterator it = img.begin<Vec3b>();
    Mat_<Vec3b>::iterator it_end = img.end<Vec3b>();
    while (it != it_end)
    {
        (*it)[0] = 255 - (*it)[0];
        (*it)[1] = 255 - (*it)[1];
        (*it)[2] = 255 - (*it)[2];
        it++;
    }
}

测量运行时间

  • cv::getTickCount():返回自某个事件以来系统CPU的滴答声
  • cv::getTickFrequency():返回CPU在一秒内发出多少次滴答声

测量两个操作之间经过的时间:

cout.setf(ios_base::fixed, ios_base::floatfield);
double t = (double)getTickCount();
// do something...
t = ((double)getTickCount() - t / getTickFrequency()) * 1000;
cout << "Times passed in seconds: " << t << endl;
posted @ 2022-01-17 19:34  TNTksals  阅读(41)  评论(0编辑  收藏  举报