Ask Your Question
1

can not draw rectangle simultaneously

asked 2012-10-22 23:01:28 -0600

muhammet_Ali gravatar image

updated 2017-09-24 11:47:39 -0600

When ı executed code program is not working correctly.I want to start to draw a rectangle when mouse lButton is clicked and finish drawing when lbutton is up. when moving the mouse ,nothing will happen but it have to increase width and height of box.The problem is exactly that: image appearing and first time ( sometimes 2 times ) I am drawing rectangle.but it doesn t seem on screen when I close image window it automatically appears with rectangle. So after restarting image window I can only have one or two rectangles.

Why are there only rectangles?

Why are they occuring when image window restarts?

#include<opencv\cv.h>
#include<opencv\highgui.h>

using namespace cv;
bool drawing=false;
CvRect box;

void drawbox(IplImage * img,CvRect rect )
{
    cvRectangle(img,cvPoint(box.x,box.y),cvPoint(box.x+box.width,box.y+box.height),cvScalar(0,0,200));
}

void mouse( int even,int x,int y,int flag,void * param)
{
    IplImage* out = ( IplImage * ) param;

    switch (even)
    {
    case CV_EVENT_LBUTTONDOWN:
        drawing=true;
        box=cvRect(x,y,0,0);
        break;
    case CV_EVENT_MOUSEMOVE:
        if (drawing)
        {
            if( x>box.x )
                box.width=x-box.x;
            else
                box.width=box.x-x;
            if(y>box.y)
                box.height=y-box.y;
            else
                box.height=box.y-y;
        }
        break;
    case EVENT_LBUTTONUP:
        drawing = false;
        drawbox(out,box);
        break;
    }
}

void main()
{
    IplImage * img= cvLoadImage("c:/lena.jpg");
    box=cvRect(-1,-1,0,0);
    cvNamedWindow("pencere");
    cvSetMouseCallback("pencere",mouse,(void*) img);
    while (true)
    {
        cvShowImage("pencere",img);
        if(drawing) drawbox(img,box); // what changes if I delete this line
        cvWaitKey();
    }
}
edit retag flag offensive close merge delete

1 answer

Sort by » oldest newest most voted
3

answered 2012-10-23 01:27:42 -0600

Vladislav Vinogradov gravatar image

You should call cvWaitKey with some delay:

cvWaitKey(10);

When you call cvWaitKey without parameter it means "wait forever while not key pressed".

edit flag offensive delete link more

Comments

1

yes it worked.Thank you very much.

muhammet_Ali gravatar imagemuhammet_Ali ( 2012-10-23 15:51:34 -0600 )edit
1

@muhammet_Ali, I suggest you to accept the answer :)

Kirill Kornyakov gravatar imageKirill Kornyakov ( 2012-10-24 02:36:16 -0600 )edit

Question Tools

Stats

Asked: 2012-10-22 23:01:28 -0600

Seen: 1,471 times

Last updated: Oct 23 '12