I want to hold a filled rectangle in a window, but failed. Please help me.
in
Integration and Hardware
•
1 year ago
The code can be built and work. But it does not work as I want. I want to use the mouse to draw a rectangle in a window. When the button pressed, it started to draw. When the button released, the final rectangle should be filled and keep in the window. I examine the code carefully and I really do not know why it does not work in that way. Please tell me. Thank you a lot!
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
#include <iostream>
using namespace std;
CvRect rect;
bool g_press = false;
void my_mouse_callback(int event, int x, int y, int flags, void* param);
int main(){
IplImage *img = cvCreateImage(cvSize(500, 500), 8, 3);
cvZero(img);
cvAddS(img, cvScalarAll(255), img);
IplImage *temp = cvCloneImage(img);
cvNamedWindow("FUN");
cvSetMouseCallback("FUN", my_mouse_callback, (void*) temp);
cout<<1<<endl;
while(1){
if(g_press) {
temp = cvCloneImage(img);
cvRectangle(temp, cvPoint(rect.x, rect.y), cvPoint(rect.x+rect.width, rect.y+rect.height), CV_RGB(50,50,50));
}
cvShowImage("FUN", temp);
if(cvWaitKey(15) == 27) break;
}
cvReleaseImage(&img);
cvDestroyWindow("FUN");
}
void my_mouse_callback(int event, int x, int y, int flags, void* param){
IplImage* img = (IplImage*) param;
switch(event){
case CV_EVENT_MOUSEMOVE:
{
if(g_press == true){
rect.width = x - rect.x;
rect.height = y - rect.y;
}
}break;
case CV_EVENT_LBUTTONDOWN:
{
g_press = true;
rect.x = x;
rect.y = y;
rect.height = rect.width = 0;
}break;
case CV_EVENT_LBUTTONUP:
{
g_press = false;
if(rect.width < 0){
rect.x += rect.width;
rect.width *= -1;
}
if(rect.height <0){
rect.y += rect.height;
rect.height *= -1;
}
cvRectangle(img, cvPoint(rect.x, rect.y), cvPoint(rect.x+rect.width, rect.y+rect.height), CV_RGB(50,50,50), CV_FILLED);
//By this statement, I want to fill the final rectangle and hold it in the window. I examined it for several times and I did not find mistakes. I just want to know the reason.
}break;
}
}
1