《视觉slam十四讲》初学小白笔记(4)

    技术2022-08-05  76

    opencv的简单使用

    #include<iostream> #include<chrono> using namespace std; #include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> int main(int argc,char** argv){ //默认构造函数,创建矩形存储图像 cv::Mat image; //读取指定路径下的图片 image=cv::imread(argv[1]); //判断图像文件是否正确读取 if(image.data==nullptr){ cout<<"文件"<<argv[1]<<"不存在"<<endl; return 0; } //文件顺利读取,首先输出一些基本信息 cout<<"图像宽度为:"<<image.cols<<",高度为:"<<image.rows<<",通道数为:"<<image.channels()<<endl; cv::imshow("image",image); cv::waitKey(0);//不加这一句,图片无法显示出来 表示程序会无限制的等待用户的按键事件 //判断image的类型 if(image.type()!=CV_8UC1&&image.type()!=CV_8UC3){ //CV_8UC1彩色图片,CV_8UC3灰色图片 //如果图像不符合要求 cout<<"请输入一张彩色或灰色图片"<<endl; return 0; } //遍历图像,可用于随机访问像素 //使用std::chrono给算法计时 chrono::steady_clock::time_point t1=chrono::steady_clock::now(); for(size_t y=0;y<image.rows;y++){ for(size_t x=0;x<image.cols;x++){ //访问位于(x,y)处的像素 //用cv::Mat::ptr获得图像的行指针 unsigned char* row_ptr=image.ptr<unsigned char>(y);//row_ptr为第y行的头指针 unsigned char* data_ptr=&row_ptr[x*image.channels()];//data_ptr指向待访问的像素数据 //输出该像素的每一个通道,如果是灰度图只有一个通道 for(int c=0;c!=image.channels();c++){ unsigned char data=data_ptr[c];//data为I(x,y)第c个通道的值 } } } chrono::steady_clock::time_point t2=chrono::steady_clock::now(); chrono::duration<double> time_used=chrono::duration_cast<chrono::duration<double>>(t2-t1); cout<<"图像遍历用时:"<<time_used.count()<<" s"<<endl; cv::waitKey(0); //cv::Mat的拷贝 //直接赋值 cv::Mat image_brother=image; image_brother(cv::Rect(0,0,100,100)).setTo(0);//将左上角100*100处像素置0(左上角黑一块) cv::imshow("image",image); //直接赋值会导致原图像也跟着改变 cv::waitKey(0); //clone函数来拷贝 cv::Mat image_clone=image.clone(); image_clone(cv::Rect(0,0,200,200)).setTo(255); cv::imshow("image",image); //clone函数不会改变原图像 cv::imshow("image clone",image_clone); cv::waitKey(0); cv::destroyAllWindows(); return 0; }

    运行结果

    Processed: 0.015, SQL: 9