美文网首页
openCV实现图片像素点采集

openCV实现图片像素点采集

作者: 此间不留白 | 来源:发表于2021-03-13 15:58 被阅读0次

    《learning opencv》ex8-2 解决方案

    有如下任务:

    1. 读取并显示一张图像,当鼠标左键点击图片时,在图片上显示当前位置的像素点
    2. 鼠标右键点击图像时,记录鼠标所点位置的坐标和对应像素点,并保存在文本文件中

    针对以上任务,利用C++实现的代码如下所示:

    
    #include<iostream>
    #include<opencv2/opencv.hpp>
    #include<opencv2/highgui/highgui.hpp> 
    #include<sstream>
    #include<fstream>
    using namespace cv;
    
    /*
    2. create a program that reads in and displays an image.When the user's mouse clicks on the image,read in the corresponding
    pixel values(blue,green,red) and write those values as text to the screen at the mouse location
     a. For the program of Ex2,display the mouse coordinates of the individual image when clicking anywhere within the three-image
        display.
    
    */
    
    void HandlerMouseEvent(int event, int x, int y, int flags,void* p)
    {
        Mat img = (*static_cast<Mat*>(p)); //获取当前图像
        Mat img_clone = img.clone();
         
    
        std::string filename = "coord_pixel.txt";  //文件名
        std::fstream out_file;
    
    
        if (event == EVENT_LBUTTONDOWN) //得到图像像素值
        {
            int blue = img_clone.at<Vec3b>(y, x)[0];
            int green = img_clone.at<Vec3b>(y, x)[1];
            int red = img_clone.at<Vec3b>(y, x)[2];
            std::stringstream s_str; //格式化字符串 像素值
            s_str << "(" << blue << "," << green << "," << red << ")";
            std::string showText = s_str.str();
    
            putText(img_clone, showText, Point(x, y), 0, 1.0, Scalar(0, 0, 255), 1, 8, 0);
            imshow("ex2", img_clone);
    
        }
        else if (event == EVENT_RBUTTONDOWN) //新加入坐标和像素值保存至map中
        {
            int blue = img_clone.at<Vec3b>(y, x)[0];
            int green = img_clone.at<Vec3b>(y, x)[1];
            int red = img_clone.at<Vec3b>(y, x)[2];
            std::stringstream s_str; //格式化字符串 像素值
            s_str << "(" << blue << "," << green << "," << red << ")";
            std::string showText = s_str.str();
    
            std::stringstream s_coordinate;  //格式化字符串,坐标
            s_coordinate << "(" << x << "," << y << ")";
            std::string str_coordinate = s_coordinate.str();
            out_file.open(filename, std::fstream::app | std::fstream::out);
            if (!out_file)
            {
                std::cerr << "文件打开失败" << std::endl;
                exit(0);
            }
            out_file << str_coordinate << ": " << showText << std::endl;
    
    
        }
        
    }
    int main()
    {   
        //加载一副图像,并创建一个窗口
        Mat img = imread("ex2.jpg");
        namedWindow("ex2");
        setMouseCallback("ex2", HandlerMouseEvent, &img);
        HandlerMouseEvent(0, 0,0,0,&img);
        
        imshow("ex2", img);
        waitKey();
        
        return 0;
    }
    
    

    实现效果图如下:



    记录的坐标点效果:


    相关文章

      网友评论

          本文标题:openCV实现图片像素点采集

          本文链接:https://www.haomeiwen.com/subject/hcpxcltx.html