OpenCV简单图像处理示例(cmake)

  1. 程序testOpenCV.cpp:读取图像,显示图像,滤波,降采样,存图像,读像素值

    #include<iostream>
    #include<opencv2/opencv.hpp>
    using namespace std;
    int main(int argc,char **argv)
    {
    	if(argc==1)
    	{
    		cout<<"usage: ./testOpenCV <Image_Path>\n";
    		return 1;
    	}
    
    	cv::Mat image_raw;
    	//读取图像
    	image_raw=cv::imread(argv[1],1); //1:彩色图     0:灰度图     -1:带深度的图
    
    	if(image_raw.empty())
    	{
    		cout<<"No image data \n";
    		return 1;
    	}
        //创建个显示窗口
    	cv::namedWindow("window0",cv::WINDOW_AUTOSIZE);
    	//显示图像
    	cv::imshow("window0",image_raw);
    
    	cv::Mat image_gray;
    	cv::cvtColor(image_raw,image_gray,CV_BGR2GRAY);//RGB图转灰度图
    	cv::namedWindow("window1",cv::WINDOW_AUTOSIZE);
    	cv::imshow("window1",image_gray);
    
    	cv::Mat image_pyrDown1;
    	cv::pyrDown(image_gray,image_pyrDown1);//滤波和降采样(大小变为原来1/2)
    	cv::namedWindow("window2",cv::WINDOW_AUTOSIZE);
    	cv::imshow("window2",image_pyrDown1);
    
    	cv::Mat image_pyrDown2;
    	cv::pyrDown(image_pyrDown1,image_pyrDown2);//再次滤波和降采样
    	cv::namedWindow("window3",cv::WINDOW_AUTOSIZE);
    	cv::imshow("window3",image_pyrDown2);
    
    	cv::imwrite("gray_pyrdown_image.jpg",image_pyrDown2);  //写,存储图像
    
    	cv::Mat image_canny;
    	cv::Canny(image_pyrDown2,image_canny,10,100,3,true);//Canny边缘检测
    	cv::namedWindow("window4",cv::WINDOW_AUTOSIZE);
    	cv::imshow("window4",image_canny);
    
    	cv::imwrite("pyrdown_canny_image.jpg",image_canny);  //写,存储图像
    
    	//读取像素值(RGB图)
    	int length=image_raw.cols-1;//  .cols,.rows 访问图像的列数(长)和行数(高)
    	int high=image_raw.rows-1;
    	cout<<"length = "<<length<<endl<<"high = "<<high<<endl;
    	for (int i=0;i<4;i++)
    	{
    		for(int j=0;j<3;j++)
    		{
    			cv::Vec3b pixel=image_raw.at<cv::Vec3b>(i,j); //(列,行)
    			cout<<"pixel["<<i<<","<<j<<"]"<<" value (B,G,R): ("<<(int)pixel[0]<<" , "<<(int)pixel[1]<<" , "<<(int)pixel[2]<<" )"<<endl;
    		}
    	}
    
    	//读取像素值(灰度图)
    	for (int i=0; i<4; i++)
    	{
    		for(int j=0; j<3; j++)
    		{
    			uchar pixel=image_gray.at<uchar>(i,j);
    			cout<<"pixel["<<i<<","<<j<<"]"<<" value (gray): ("<<(short)pixel<<")"<<endl;
    		}
    	}
    
    
    
    	cv::waitKey(0);
    
    	return 0;
    }
    
  2. CMakeLists.txt文件

    cmake_minimum_required(VERSION 3.0)
    project(testOpenCV)
    find_package(OpenCV 3  REQUIRED)
    
    message("OpenCV version::::${OpenCV_VERSION}")
    message("OpenCV_INCLUDE_DIRS:::::${OpenCV_INCLUDE_DIRS}")
    message("OpenCV_LIBS::::::::${OpenCV_LIBS}")
    
    set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
    
    include_directories(${OpenCV_INCLUDE_DIRS})
    
    add_executable(${PROJECT_NAME} src/testOpenCV.cpp)
    
    target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})
    
上一篇:CMake语法—普通变量与函数(Normal Variable And Function)


下一篇:Graphviz(02) 汉字subgraph不显示汉字的处理