OpenCV-Mat方式的获取图片的像素(一)

来源:互联网 发布:福建医科大学好吗知乎 编辑:程序博客网 时间:2024/05/29 04:02

作为OpenCV基础知识中的重中之重,像素值的读写需要我们很用心的掌握。

1、读取原图


    const char filename[] = "/Users/linwang/Desktop/Lena.png";    Mat Im = imread(filename);    cout<<"Im.dims  = "<<Im.dims<<endl;    cout<<"Im.rows  = "<<Im.rows<<endl;    cout<<"Im.cols  = "<<Im.cols<<endl;    cout<<"Im.channels = "<<Im.channels()<<endl;    cout<<"Im.step[0] = " <<Im.step[0]<<endl;    cout<<"Im.step[1] = " <<Im.step[1]<<endl;    cout<<"Im.Elemsize = "<<Im.elemSize()<<endl;    //一个像素点的大小  CV_8U3C=1*3    cout<<"Im.Elemsize1 = "<<Im.elemSize1()<<endl;  //数据类型的大小 UCHAR = 1 (ElemSize / Channel)    namedWindow("Old-Lena");    imshow("Old-Lena", Im);






2、最朴素的指针偏移,读取像素点值,修改Lena


    /*2.采用最朴素的方式修改Lena,获得Test*/    Mat test_im = Im.clone();    for (int i = 0; i<test_im.rows; i++)    {        uchar * ptr = test_im.data + i * test_im.step;  //step 是一行的数据长度        for(int j = 0;j<test_im.step;j++)        {            *(ptr + j)     = i%255;  //Bule        }    }    cvNamedWindow("Test-Lena");    imshow("Test-Lena", copy_im);


3、采用C++的Vec来读取像素点数据


   /*1.采用C++模版 STL的方式 修改Lena原图,得到New*/    Mat copy_im = Im.clone();    for (int i = 0; i<copy_im.rows; i++)    {        for(int j = 0;j<copy_im.cols;j++)        {            Vec3b pixel;            pixel[0] = i%255; //Blue            pixel[1] = j%255; //Green            pixel[2] = 0;     //Red            copy_im.at<Vec3b>(i,j) = pixel;        }    }    cvNamedWindow("New-Lena");    imshow("New-Lena", copy_im);






4、迭代器方式遍历图像

    /*3.迭代器方法遍历图像像素*/    Mat IterIm = Im.clone();    MatIterator_<Vec3b> IterBegin,IterEnd;   //迭代器    for(IterBegin = IterIm.begin<Vec3b>(),IterEnd = IterIm.end<Vec3b>();IterBegin!=IterEnd;++IterBegin)    {        (*IterBegin)[0] = rand()%255;        (*IterBegin)[1] = rand()%255;        (*IterBegin)[2] = rand()%255;    }    cvNamedWindow("IterImg");    imshow("IterImg", IterIm);    cvWaitKey(0);


阅读全文
0 0
原创粉丝点击