zoukankan      html  css  js  c++  java
  • 《学习OpenCV》课后习题解答9

    题目:(P126)
    创建一个程序,使其读入并显示一幅图像。当用户鼠标点击图像时,获取图像对应像素的颜色值(BGR),并在图像上点击鼠标处用文本将颜色值显示出来。

    解答:
    本题关键是会用cvGet2D获得BGR值,以及会用鼠标点击事件和回调函数,还有显示文本值。

    #include<cv.h>
    #include<highgui.h>
    #include<iostream>
    
    using namespace std;
    char* str = (char*)malloc(30 * sizeof(char*));
    void myMouseCallback(
        int event,
        int x,
        int y,
        int flags,
        void* param
        );
    int main(int argc, char* argv[])
    {
        IplImage* img = cvLoadImage(argv[1]);
        cvNamedWindow("获取图像某一点的颜色分量", 1);
        cvShowImage("获取图像某一点的颜色分量", img);
        while (1)
        {
            cvSetMouseCallback(
                "获取图像某一点的颜色分量",
                myMouseCallback,
                (void*)img
                );
            if (cvWaitKey(100) == 27)
                break;
        }
        cvReleaseImage(&img);
        cvDestroyWindow("获取图像某一点的颜色分量");
        return 0;
    }
    void myMouseCallback(
        int event,
        int x,
        int y,
        int flags,
        void* param
        ) {
        IplImage* img = (IplImage*)param;
        if (event == CV_EVENT_LBUTTONDOWN)
        {
            CvScalar s;
            s = cvGet2D(img, x, y);//返回(x,y)的RGB值
    
    
            CvFont cvf;
            cvInitFont(&cvf, CV_FONT_HERSHEY_PLAIN, 1, 1, 0, 1, 8);
            double r = s.val[0];
            double g = s.val[1];
            double b = s.val[2];
            memset(str, 0, 30);
            sprintf(str, "B:%.0f,G:%.0f,R:%.0f", b, g, r);
            cout << "B:" << b << ",G:" << g << ",R:" << r << endl;
            cvPutText(img,
                str,
                cvPoint(x, y),
                &cvf,
                cvScalar(255, 0, 0)
                );
            cvShowImage("获取图像某一点的颜色分量", img);
        }
    }
    
    
  • 相关阅读:
    浏览器渲染原理
    前端日常工作性能优化条例
    前端的发展历程
    【YOLO-V1】You Only Look Once: Unified, Real-Time Object Detection
    ModuleNotFoundError: No module named 'keras_retinanet.utils.compute_overlap'
    python学习笔记:线性回归
    软件安装笔记5:navicat for mysql及其简单应用
    python学习笔记39:sklearn
    python学习笔记38:matplotlib
    python学习笔记37:pandas
  • 原文地址:https://www.cnblogs.com/huahai/p/7271054.html
Copyright © 2011-2022 走看看