我有一个设置窗口,用户可以按下按钮创建一个新窗口,您可以在其中选择图像区域。选择区域后,用户可以按鼠标右键将其坐标保存在xml文件中。这个"选择区域"保存xml文件后,窗口应自动关闭。
我的问题是我无法在新窗口中调用cv :: destroyWindow而不会导致整个程序崩溃。我想过先用setMouseCallback( "imageWindow", NULL, NULL );
删除鼠标事件,但这并不能防止崩溃。
以下是我的代码的重要部分:
void Settings::on_buttonXML_clicked(){
cv::VideoCapture webcam;
webcam.open(INDEX);
webcam.read(src);
color = Scalar(0,0,255);
coor_num = 0;
xmlPath="C:/myregion.xml";
cv::namedWindow("imageWindow", CV_WINDOW_AUTOSIZE );
cv::imshow("imageWindow", src);
cv::setMouseCallback( "imageWindow", onMouse, this );
cv::waitKey(0);
}
void Settings::onMouse(int event, int x, int y, int, void* userdata) {
Settings* settings = reinterpret_cast<Settings*>(userdata);
settings->onMouse(event, x, y);
}
void Settings::onMouse(int event, int x, int y) {
if (event == CV_EVENT_LBUTTONUP) {
cv::Point2f p(x, y);
coor.push_back(p);
cv::line(src,p,p,color);
if(coor.size()>1)
cv::line(src, p, coor[coor.size()-2], color);
cv::imshow("imageWindow", src);
}
else if (event == CV_EVENT_RBUTTONUP && coor.size()>2){
cv::line(src, coor[0], coor[coor.size()-1], color);
getPointsInContour(coor);
cv::imshow("imageWindow", src);
cv::waitKey(500);
cv::setMouseCallback( "imageWindow", NULL, NULL );
cv::destroyWindow("imageWindow");
}
}
void Settings::savePointsAsXML(vector<Point2f> & contour){
TiXmlDocument doc;
TiXmlDeclaration decl("1.0", "", "");
doc.InsertEndChild(decl);
for(int i = 0; i < contour.size(); i++)
{
TiXmlElement point("point");
point.SetAttribute("x",contour[i].x);
point.SetAttribute("y",contour[i].y);
doc.InsertEndChild(point);
}
if(doc.SaveFile(xmlPath.c_str()))
cout << "file saved succesfully.\n";
else
cout << "file not saved, something went wrong!\n";
}
void Settings::getPointsInContour(vector<Point2f> & contour){
vector<Point2f> insideContour;
for(int j = 0; j < src.rows; j++){
for(int i = 0; i < src.cols; i++){
Point2f p(i,j);
if(pointPolygonTest(contour,p,false) >= 0) // yes inside
insideContour.push_back(p);
}
}
cout << "# points inside contour: " << insideContour.size() << endl;
savePointsAsXML(insideContour);
}
我认为问题可能出在cv::waitKey(0);
函数中的Settings::on_buttonXML_clicked()
。我不确定为什么我需要在那里拨打waitKey(0)
,但我知道如果waitKey()不存在或者参数高于0,我会立即崩溃。我在这里缺少什么?