Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Drawing rectangle OpenCV : don't understand a detail

Hi everybody,

ther is a detail that i can't understand it,

here is the code for drawing rectangle in the first image captured from cam. it work very fine, BUT i can't understand one thing :

in the main part, and precisely in the while loop, it is not supposed that if i don't use anymore the mouse, the temp image will be the same as original image after one loop at less ?

Untill now, all rectangles that i drawed still showen !!

Thank you for your comment;

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>


using namespace cv;
using namespace std;

void my_mouse_callback( int event, int x, int y, int flags, void* param );

bool destroy=false;
Rect box;
bool drawing_box = false;

void draw_box(Mat * img, Rect rect)
{
  rectangle(*img, Point(box.x, box.y), Point(box.x+box.width,box.y+box.height),Scalar(0,0,255) ,2);

  Rect rect2=Rect(box.x,box.y,box.width,box.height);
}

// Implement mouse callback
void my_mouse_callback( int event, int x, int y, int flags, void* param )
{
  Mat* frame = (Mat*) param;

  switch( event )
  {
      case CV_EVENT_MOUSEMOVE:
      {
          if( drawing_box )
          {
              box.width = x-box.x;
              box.height = y-box.y;
          }
      }
      break;

      case CV_EVENT_LBUTTONDOWN:
      {   drawing_box = true;
          box = Rect( x, y, 0, 0 );
      }
      break;

      case CV_EVENT_LBUTTONUP:
      {   drawing_box = false;
          if( box.width < 0 )
          {   box.x += box.width;
              box.width *= -1;      
     }

          if( box.height < 0 )
          {   box.y += box.height;
              box.height *= -1; 
      }
              draw_box(frame, box); 
          }
      break;

      default:
      break;
   }
}

int main()
{
  String name = "Box Example";
  namedWindow( name );
  box = Rect(0,0,1,1);

  VideoCapture capture(0) ;
  if (!capture.isOpened())
  {
    printf("!!! Failed CaptureFromCAM\n");
    return 1;
  }

  Mat image;
  capture.read(image);
  if (!image.data)
  {
    printf("!!! Failed \n");
    return 2;
  }

  Mat temp = image.clone();

  setMouseCallback(name, my_mouse_callback, &image);

  while( 1 )
  {
    temp = image.clone();
    if (drawing_box)
        draw_box(&temp, box);

    imshow(name, temp);
    if (waitKey(15) == 27)
    break;
  }
  return 0;
}