【4】opencv像素遍历的五种方法

#include 
#include 
using namespace std;
int main()
{
    //这里png是四个通道,只是改掉其中的三个通道
    cv::Mat MrMKG_0;
    MrMKG_0 = cv::imread("C:/Users/86136/Desktop/opencv学习/[004]像素遍历和访问/0001.png");
    cv::namedWindow("图片输出样例");
    cv::imshow("图片输出样例", MrMKG_0);
    cv::waitKey(10);

    //【1】下标M.at(i,j)
    int i, j;
    for (i = 0;i < 1000; i++)
    {
        for (j = 0; j < 1000; j++)
        {
            MrMKG_0.at(i, j)[0] = 255;
            MrMKG_0.at(i, j)[0] = 0;
            MrMKG_0.at(i, j)[0] = 255;

       }
    }
        
    cv::namedWindow("图片输出样例");
    cv::imshow("图片输出样例", MrMKG_0);
    cv::waitKey(90);

    
    /*
    【2】利用指针(不熟)
    这里所做到的是颜色反转
    */
    cv::Mat MrMKG_1 = MrMKG_0.clone();
    int row = MrMKG_1.rows;
    int col = MrMKG_1.cols;
    int nStep = MrMKG_1.cols * MrMKG_1.channels();

    for (int i = 0; i < row; i++)
    {
        uchar* pSrcData = MrMKG_0.ptr(i);
        uchar* pResuiltData = MrMKG_1.ptr(i);

        for (int j = 0; j < nStep; j++)
        {
            pResuiltData[j] = cv::saturate_cast(255 - pSrcData[j]);
            //saturate_cast防溢出保护
        }
    }
    cv::namedWindow("图片输出样例");
    cv::imshow("图片输出样例", MrMKG_1);
    cv::waitKey(90);

    /*
    【3】迭代器MatIterator_
    迭代器MatIterator_速度是五种方式里面的最慢的,操作方式比较复杂。不推荐使用。
    (写这儿也就图一乐)
    */
cv::Mat temp = MrMKG_0.clone();
cv::MatConstIterator_ srcIterStart = MrMKG_0.begin();
cv::MatConstIterator_ srcIterEnd = MrMKG_0.end();
cv::MatIterator_ resIterStart = temp.begin();
cv::MatIterator_ resIterEnd = temp.end < cv::Vec3b > ();

while (srcIterStart != srcIterEnd)
{

    (*resIterStart)[0] = 255 - (*srcIterStart)[0];
    (*resIterStart)[1] = 255 - (*srcIterStart)[1];
    (*resIterStart)[2] = 255 - (*srcIterStart)[2];
    srcIterStart++;
    resIterStart++;
}


    /*
     【4】isContinouous
      应用于连续的图像
    */
int row_1 = MrMKG_0.rows;
int col_1 = MrMKG_0.cols;

cv::Mat temp_1 = MrMKG_0.clone();
// 判断是否是连续图像,即是否有像素填充
if (MrMKG_0.isContinuous() && temp_1.isContinuous())
{
    row_1 = 1;
    // 按照行展开
    col_1 = col_1 * MrMKG_0.rows * MrMKG_0.channels();
}
// 遍历图像的每个像素
for (int i = 0; i < row_1; i++)
{
    // 设定图像数据源指针及输出图像数据指针
    const uchar* pSrcData = MrMKG_0.ptr(i);
    uchar* pResultData = temp_1.ptr(i);

    for (int j = 0; j < col; j++)
    {
        *pResultData++ = 255 - *pSrcData++;
    }
}

    cv::namedWindow("图片输出样例");
    cv::imshow("图片输出样例", temp_1);
    cv::waitKey(9000);


//【5】LTU查表法(过几天学)

}

你可能感兴趣的:(opencv学习笔记,opencv,计算机视觉,c++,学习)