Ask Your Question

how to use cv::setMouseCallback in a c++ class

asked 2013-01-11 09:23:36 -0500

engine gravatar image

updated 2013-01-14 01:56:09 -0500

Vladislav Vinogradov gravatar image

Hi ! I'm trying to use the cv::setMouseCallback to crop a frame. it just doesn't work can any body tell the whole program carshes when I use it:

 class Mainthread{
  cv::Mat m_part;

public :
     static void mouseHandler(int event,int x,int y, int flags,void* param);
     static void draw_box(cv::Mat,cv::Rect);         
     void gettingROI();    
     static cv::Rect theBox;
 void MainThread::gettingROI(){
m_part = stream.getframe();
name = "roi";
 cv::Rect MainThread::theBox =  cv::Rect(0,0,0,0);
 void MainThread::mouseHandler(int event,int x , int y , int flags, void* param){
cv::Mat* pimage = (cv::Mat*) param;
cv::Mat image = * pimage;

switch( event ){
        if( drawing_box ){
            theBox.width = x-theBox.x;
            theBox.height = y-theBox.y;

After @Vladislav suggestion I changed my code, it work now but I have a problem with cv::Rect theBox any idea

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted

answered 2013-01-11 12:23:10 -0500

Vladislav Vinogradov gravatar image

You pass pointer to local variable part into cv::setMouseCallback. This variable will be destroyed in the end of gettingROI function. And in mouseHandler you will get bad pointer. Make part variable a class member:

class Mainthread
    cv::Mat m_part;
public :
     static void mouseHandler(int event,int x,int y, int flags,void* param);
     void gettingROI();    
void MainThread::gettingROI()
    m_part = stream.getframe();
    name = "roi";
    cv::imshow(name, m_part);
    cv::setMouseCallback(name, mouseHandler, &m_part);
edit flag offensive delete link more


@Vladislav thanks so much for your help it work actually , but I need this function to draw a rect on a frame how should I declar my cv::rect box please see my edited Question, and thanks again for ur help

engine gravatar imageengine ( 2013-01-14 01:43:58 -0500 )edit

answered 2013-01-14 20:07:14 -0500

xiaojidan gravatar image

updated 2013-01-14 20:09:00 -0500

Good!!! could you give me a complete code? I am interested in it, so I want to understand deeply.
My email is

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower


Asked: 2013-01-11 09:23:36 -0500

Seen: 13,636 times

Last updated: Jan 14 '13