openCV鼠标事件学习

opencv中鼠标事件的学习


代码

// MouseOperate.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;

Rect g_rect;
bool g_ispaint;
void drawRect(Mat &img ,Rect rect); //定义画矩形函数
void onMousePaint(int event,int x,int y,int flags,void* param);//定义鼠标回调函数
int _tmain(int argc, _TCHAR* argv[])
{
    /*int bb = 20;
    void *a ;
    a = &bb;
    int c;
    int *d = (int*)a;
    cout<<"bb="<<bb<<endl;
    cout<<"*d="<<*d<<endl;
    while(1);
    return 0;
    */

    char *windowName = "卫庄";
    Mat img = imread("D:\\large.png");
    namedWindow(windowName);
    //测试是否读取成功
//  imshow(windowName,img);
//  waitKey(0);
    //绑定鼠标事件
    setMouseCallback(windowName,onMousePaint,(void*)&img);

    while(1){//循环读取图片并显示
        imshow(windowName,img);
        if(waitKey(10)==27)
            break;
    }
    return 0 ;
}

void onMousePaint(int event,int x,int y,int flags,void* param){
    Mat img = *(Mat*)param;
    switch(event){
    case EVENT_LBUTTONDOWN:
        g_ispaint = true;
        g_rect = Rect(x,y,0,0);
        break;
    case EVENT_MOUSEMOVE:
        if(g_ispaint){
            g_rect.width = x-g_rect.x;
            g_rect.height = y - g_rect.y;
        }

        break;
    case EVENT_LBUTTONUP:
        g_ispaint = false;
        if(g_rect.width<0){
            g_rect.x = g_rect.x+g_rect.width;
            g_rect.width = g_rect.width*-1;
        }
        if(g_rect.height<0){
            g_rect.y+= g_rect.height;
            g_rect.height*=-1;
        }
        drawRect(img,g_rect);
        break;
    }
}
void drawRect(Mat &img ,Rect rect){
    rectangle(img,Point(rect.x,rect.y),Point(rect.x+rect.width,rect.y+rect.height),Scalar::all(255));
}

细节学习

1.关于void*
void*转化为其他类型可以用此思想:先将void*的变量转换为需要转换的类型的指针。然后再解引用即可。如上的* (Mat*)param
2. 回调函数中的x,y为图片的坐标而非窗口的坐标


案例图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值