user2799508
user2799508

Reputation: 848

OpenCV: Image window keeps hanging and not responding

The following code draws a line connecting two points user clicks on an image:

using namespace cv;
using namespace std;


void onMouse(int evt, int x, int y, int flags, void* param) {
    if(evt == CV_EVENT_LBUTTONDOWN) {
        std::vector<cv::Point>* ptPtr = (std::vector<cv::Point>*)param;
        ptPtr->push_back(cv::Point(x,y));
    }
}

int main()

{

std::vector<Point> points;

cv::namedWindow("Output Window");

Mat frame = cv::imread("chhha.png");

cv::setMouseCallback("Output Window", onMouse, (void*)&points);
int X1=0, Y1=0, X2=0, Y2=0; 

while(1)
{
    cv::imshow("Output Window", frame);

    if (points.size() > 1) //we have 2 points
    {

        for (auto it = points.begin(); it != points.end(); ++it)
        {


        }

        break;
    }
    waitKey(10);
}

//just for testing that we are getting pixel values 
X1=points[0].x; 
X2=points[1].x; 


Y1=points[0].y; 
Y2=points[1].y; 
cout<<"First and second X  coordinates are given below"<<endl;
cout<<X1<<'\t'<<X2<<endl; 

cout<<"First and second Y coordinates are given below"<<endl;
cout<<Y1<<'\t'<<Y2<<endl; 


 // Now let us draw a line on the image 
  line( frame, points[0], points[1], 'r',  2, 8 );
  cv::imshow("Output Window", frame);

  waitKey( 10 );

getch(); 

return 0;  
}

The problem is the program is not exiting if I close (by clicking the cross button on the image on top right )the "Output Window", instead it hangs and says Not responding.

How do I remove this problem ?

Upvotes: 1

Views: 920

Answers (1)

Bull
Bull

Reputation: 11941

The reason that your application does not exit is that you have an infinite loop, and clicking on the cross to close a window does nothing to break that loop. One way to exit is to test for a key being pressed, e.g.

    while(true)
    {
        ...
        char c = cv::waitKey(10);
        if(c == 'q')
            break;
    }

BTW, assuming you are on windows, if a window is destroyed waitKey() intercepts a WM_DESTROY message. In this case waitKey() returns message.wParam, but the windows doco for WM_DESTROY says This parameter is not used. It looks like a bug to me, but it might be worth investigating whether waitKey() returns a consistent value when the window is closed - normally -1 is returned if no key is pressed.

Upvotes: 1

Related Questions