1 // Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // GEOM GEOMGUI : GUI for Geometry component
24 // File : EntityGUI_SketcherDlg.cxx
25 // Author : Renaud NEDELEC, Open CASCADE S.A.S.
28 #include "EntityGUI_FeatureDetectorDlg.h"
29 #include <ShapeRec_FeatureDetector.hxx>
31 #include <OCCViewer_ViewWindow.h>
32 #include <OCCViewer_ViewManager.h>
34 #include <SOCC_ViewModel.h>
37 #include <GeometryGUI.h>
38 #include <EntityGUI.h>
41 #include <SUIT_Desktop.h>
42 #include <SUIT_ResourceMgr.h>
43 #include <SUIT_Session.h>
44 #include <SUIT_ViewWindow.h>
45 #include <SalomeApp_Application.h>
46 #include <LightApp_Application.h>
47 #include <LightApp_SelectionMgr.h>
49 #include <SALOME_ListIteratorOfListIO.hxx>
51 #include <SalomeApp_Study.h>
53 #include <utilities.h>
54 #include <Precision.hxx>
58 #include <TopoDS_Shape.hxx>
59 #include <TopoDS_Wire.hxx>
61 #include <BRepBuilderAPI_MakeVertex.hxx>
62 #include <BRepBuilderAPI_MakeFace.hxx>
63 #include <BRepBuilderAPI_MakePolygon.hxx>
64 #include <BRepBuilderAPI_Transform.hxx>
66 #include <AIS_TexturedShape.hxx>
67 #include <TCollection_AsciiString.hxx>
68 #include <StdSelect_DisplayMode.hxx>
70 #include <Graphic3d_MaterialAspect.hxx>
77 #include <boost/utility.hpp>
100 //=================================================================================
101 // class : EntityGUI_FeatureDetectorDlg()
102 // purpose : Constructs a EntityGUI_FeatureDetectorDlg which is a child of 'parent', with the
103 // name 'name' and widget flags set to 'f'.
104 // The dialog will by default be modeless, unless you set 'modal' to
105 // TRUE to construct a modal dialog.
106 //=================================================================================
107 EntityGUI_FeatureDetectorDlg::EntityGUI_FeatureDetectorDlg( GeometryGUI* theGeometryGUI, QWidget* parent,
108 bool modal, Qt::WindowFlags fl)
109 : GEOMBase_Skeleton(theGeometryGUI, parent, modal, fl)
111 QPixmap image0(SUIT_Session::session()->resourceMgr()->loadPixmap("GEOM", tr("ICON_SELECT")));
112 QPixmap image1(SUIT_Session::session()->resourceMgr()->loadPixmap("OCCViewer", tr("ICON_OCCVIEWER_VIEW_DUMP")));
114 setWindowTitle(tr("GEOM_DETECT_TITLE"));
116 /***************************************************************/
118 mainFrame()->GroupConstructors->setTitle(tr("GEOM_FEATURES"));
119 mainFrame()->RadioButton1->setText(tr("GEOM_CONTOURS"));
120 mainFrame()->RadioButton2->setText(tr("GEOM_CORNERS"));
121 mainFrame()->RadioButton3->setAttribute(Qt::WA_DeleteOnClose);
122 mainFrame()->RadioButton3->close();
124 // myViewGroup = new DlgRef_3Radio(centralWidget());
125 // myViewGroup->GroupBox1->setTitle(tr("GEOM_VIEW"));
126 // myViewGroup->RadioButton1->setText(tr( "GEOM_TOP" ));
127 // myViewGroup->RadioButton2->setText(tr( "GEOM_FRONT"));
128 // myViewGroup->RadioButton3->setText(tr( "GEOM_LEFT" ));
129 // myViewButtonGroup = new QButtonGroup( this );
130 // myViewButtonGroup->addButton( myViewGroup->RadioButton1, XY ); // Top view
131 // myViewButtonGroup->addButton( myViewGroup->RadioButton2, YZ ); // Front View
132 // myViewButtonGroup->addButton( myViewGroup->RadioButton3, XZ ); // Left View
134 // myViewGroup->hide();
136 // Widgets for the selection of the picture and the Region Of Interest
139 mySelectionGroup = new DlgRef_1Sel1Frame(centralWidget());
141 mySelectionGroup->PushButton1->setIcon(image0);
142 mySelectionGroup->PushButton1->setCheckable(true);
143 mySelectionGroup->PushButton1->setAutoExclusive(true);
145 mySelectionGroup->PushButton2->setIcon(image1);
146 mySelectionGroup->PushButton2->setCheckable(true);
147 mySelectionGroup->PushButton2->setAutoExclusive(true);
149 mySelectionGroup->TextLabel1->setText(tr( "GEOM_PICTURE" ));
150 mySelectionGroup->FrameLabel->setText("");
152 myOutputGroup = new DlgRef_3Radio(centralWidget());
153 myOutputGroup->GroupBox1->setTitle(tr("GEOM_DETECT_OUTPUT"));
154 myOutputGroup->RadioButton2->setText(tr( "GEOM_POLYLINE" ));
155 myOutputGroup->RadioButton1->setText(tr( "GEOM_SPLINE"));
156 myOutputGroup->RadioButton3->hide();
158 // myOutputGroup->hide(); //caché pour la demo
160 QVBoxLayout* layout = new QVBoxLayout(centralWidget());
161 layout->setMargin(0); layout->setSpacing(6);
162 // layout->addWidget( myViewGroup);
163 layout->addWidget( mySelectionGroup);
164 layout->addWidget( myOutputGroup);
166 // mainFrame()->GroupBoxName->hide();
168 // Build an instance of detection used to perform image processing operations
169 aDetector = new ShapeRec_FeatureDetector();
171 setHelpFileName( "shape_recognition_page.html" );
177 //=================================================================================
178 // function : ~EntityGUI_FeatureDetectorDlg()
179 // purpose : Destroys the object and frees any allocated resources
180 //=================================================================================
181 EntityGUI_FeatureDetectorDlg::~EntityGUI_FeatureDetectorDlg()
186 //=================================================================================
189 //=================================================================================
190 void EntityGUI_FeatureDetectorDlg::Init()
192 connect( myGeomGUI, SIGNAL( SignalCloseAllDialogs() ), this, SLOT( ClickOnCancel() ) );
193 connect( buttonOk(), SIGNAL( clicked() ), this, SLOT( ClickOnOk() ) );
194 connect( buttonApply(), SIGNAL( clicked() ), this, SLOT( ClickOnApply() ) );
195 connect( this, SIGNAL(constructorsClicked(int)), this, SLOT(ConstructorsClicked(int)));
196 connect( mySelectionGroup->PushButton2, SIGNAL( clicked() ), this, SLOT( onButtonClicked() ) );
197 connect( mySelectionGroup->PushButton1, SIGNAL( clicked() ), this, SLOT( onButtonClicked() ) );
198 // connect( myViewButtonGroup, SIGNAL( buttonClicked( int ) ), this, SLOT( onViewClicked( int ) ) );
199 connect( myGeomGUI->getApp()->selectionMgr(), SIGNAL( currentSelectionChanged() ),this, SLOT( SelectionIntoArgument() ) );
202 mySelectionGroup->PushButton1->click();
204 // SetEditCurrentArgument();
205 SelectionIntoArgument();
207 initName(tr("GEOM_CONTOURS"));
210 // myViewGroup->RadioButton1->setChecked(true);
211 myOutputGroup->RadioButton1->setChecked(true);
213 gp_Pnt aOrigin = gp_Pnt(0, 0, 0);
214 gp_Dir aDirZ = gp_Dir(0, 0, 1);
215 gp_Dir aDirX = gp_Dir(1, 0, 0);
217 aGlobalCS = gp_Ax3(aOrigin, aDirZ, aDirX);
219 myStartPnt = gp_Pnt(0,0,0);
220 myEndPnt = myStartPnt;
222 myGeomGUI->SetWorkingPlane( aGlobalCS );
223 myGeomGUI->ActiveWorkingPlane();
225 ConstructorsClicked(myConstructorId);
228 //=================================================================================
229 // function : SelectionIntoArgument()
230 // purpose : Called when selection as changed or other case
231 //=================================================================================
232 void EntityGUI_FeatureDetectorDlg::SelectionIntoArgument()
235 // TODO supprimer les lignes qui ne servent à rien le cas échéant
236 SUIT_ViewWindow* theViewWindow = getDesktop()->activeWindow();
237 std::map< std::string , std::vector<Handle(AIS_InteractiveObject)> >::iterator AISit;
238 SOCC_Viewer* soccViewer = (SOCC_Viewer*)(theViewWindow->getViewManager()->getViewModel());
240 if (!myEditCurrentArgument->isEnabled())
243 myEditCurrentArgument->setText( "" );
245 LightApp_SelectionMgr* aSelMgr = myGeomGUI->getApp()->selectionMgr();
246 SALOME_ListIO aSelList;
247 aSelMgr->selectedObjects(aSelList);
248 SALOME_ListIteratorOfListIO anIt( aSelList );
250 for( ; anIt.More(); anIt.Next() )
251 if( !anIt.Value().IsNull() )
253 myFaceEntry = anIt.Value()->getEntry();
256 if (aSelList.Extent() != 1) {
257 if (myEditCurrentArgument == mySelectionGroup->LineEdit1)
262 TopAbs_ShapeEnum aNeedType = TopAbs_FACE ;
263 GEOM::GeomObjPtr aSelectedObject = getSelected( aNeedType );
265 if ( aSelectedObject && GEOMBase::GetShape( aSelectedObject.get(), aShape ) && !aShape.IsNull() ) {
266 QString aName = GEOMBase::GetName( aSelectedObject.get() );
267 myEditCurrentArgument->setText( aName );
269 if ( myEditCurrentArgument == mySelectionGroup->LineEdit1 ) {
270 myFace = aSelectedObject;
271 AISit = soccViewer->entry2aisobjects.find(myFaceEntry.toStdString());
272 if (AISit == soccViewer->entry2aisobjects.end())
275 Handle(AIS_InteractiveObject) myAIS = (*AISit).second[0];
276 Handle(GEOM_AISShape) myAISShape;
277 if( myAIS->IsInstance( STANDARD_TYPE(GEOM_AISShape) ) ) {
278 myAISShape = Handle(GEOM_AISShape)::DownCast( myAIS );
283 std::string theImgFileName = myAISShape->TextureFile();
284 if ( theImgFileName == "" )
287 // Setting the image caracteristics
288 aDetector->SetPath( theImgFileName );
289 height = aDetector->GetImgHeight();
290 width = aDetector->GetImgWidth();
291 pictureLeft = -0.5 * width; // X coordinate of the top left corner of the background image in the view
292 pictureTop = 0.5 * height; // Y coordinate of both top corners
299 //=================================================================================
300 // function : acceptMouseEvent()
302 //=================================================================================
303 bool EntityGUI_FeatureDetectorDlg::acceptMouseEvent() const
305 return mySelectionGroup->PushButton2->isChecked();
308 //=======================================================================
309 // function : ClickOnOk()
311 //=======================================================================
312 void EntityGUI_FeatureDetectorDlg::ClickOnOk()
314 setIsApplyAndClose( true );
319 //=================================================================================
320 // function : ClickOnApply()
322 //=================================================================================
323 bool EntityGUI_FeatureDetectorDlg::ClickOnApply()
329 ConstructorsClicked(getConstructorId());
333 //=================================================================================
334 // function : onConstructorClicked(int)
336 //=================================================================================
337 void EntityGUI_FeatureDetectorDlg::ConstructorsClicked(int id)
339 MESSAGE("Constructor id ="<<id)
340 myConstructorId = id;
344 // myViewGroup->show();
345 // mySelectionGroup->show();
346 myOutputGroup->hide();
347 // mySelectionGroup->TextLabel2->setText(tr("GEOM_DETECT_ZONE"));
348 mySelectionGroup->TextLabel2->hide();
349 mySelectionGroup->Frame->hide();
350 mySelectionGroup->PushButton2->hide();
351 initName(tr("GEOM_CORNERS"));
354 // myViewGroup->hide();
355 // mySelectionGroup->hide();
356 // mySelectionGroup->show();
357 myOutputGroup->show();
358 mySelectionGroup->TextLabel2->show();
359 mySelectionGroup->Frame->show();
360 mySelectionGroup->PushButton2->show();
361 mySelectionGroup->TextLabel2->setText(tr("GEOM_COLOR_FILTER"));
362 initName(tr("GEOM_CONTOURS"));
365 // myViewGroup->hide();
366 // mySelectionGroup->hide();
367 // mySelectionGroup->show();
368 myOutputGroup->hide();
369 mySelectionGroup->TextLabel2->setText(tr(""));
370 initName(tr("GEOM_LINES"));
375 // //=================================================================================
376 // // function : onViewClicked()
378 // //=================================================================================
379 // void EntityGUI_FeatureDetectorDlg::onViewClicked(int id)
381 // gp_Pnt aOrigin = gp_Pnt(0, 0, 0);
388 // aDirZ = gp_Dir(0, 0, 1);
389 // aDirX = gp_Dir(1, 0, 0);
392 // aDirZ = gp_Dir(1, 0, 0);
393 // aDirX = gp_Dir(0, 1, 0);
396 // aDirZ = gp_Dir(0, -1, 0);
397 // aDirX = gp_Dir(1, 0 , 0);
401 // myWPlane = gp_Ax3(aOrigin, aDirZ, aDirX);
402 // myGeomGUI->SetWorkingPlane( myWPlane );
403 // myGeomGUI->ActiveWorkingPlane();
407 //=================================================================================
408 // function : onButtonClicked()
410 //=================================================================================
411 void EntityGUI_FeatureDetectorDlg::onButtonClicked()
413 QPushButton* send = (QPushButton*)sender();
414 if (send == mySelectionGroup->PushButton2)
416 mySelectionGroup->LineEdit1->setEnabled(false);
418 else if (send == mySelectionGroup->PushButton1)
420 myStartPnt = gp_Pnt(0,0,0);
421 myEndPnt = myStartPnt;
422 myEditCurrentArgument = mySelectionGroup->LineEdit1;
423 mySelectionGroup->LineEdit1->setEnabled(true);
427 //=================================================================================
428 // function : setStartPnt( const QPoint& )
430 //=================================================================================
431 void EntityGUI_FeatureDetectorDlg::setStartPnt(const gp_Pnt& theStartPnt)
433 myStartPnt = theStartPnt;
434 MESSAGE("myStartPnt = ("<<theStartPnt.X()<<", "<<theStartPnt.Y()<<")")
437 //=================================================================================
438 // function : setEndPnt( const QPoint& )
440 //=================================================================================
441 void EntityGUI_FeatureDetectorDlg::setEndPnt(const gp_Pnt& theEndPnt)
443 myEndPnt = theEndPnt;
444 MESSAGE("myEndPnt = ("<<theEndPnt.X()<<", "<<theEndPnt.Y()<<")")
445 if (setSelectionRect() && aDetector->GetImgHeight() > 0)
449 //=================================================================================
450 // function : setSelectionRect()
452 //=================================================================================
453 bool EntityGUI_FeatureDetectorDlg::setSelectionRect()
455 // Set detection rectangle in the background image coordinates system
456 double left = std::min( myStartPnt.X(), myEndPnt.X() );
457 double top = std::max( myStartPnt.Y(), myEndPnt.Y() );
458 double right = std::max( myStartPnt.X(), myEndPnt.X() );
459 double bottom = std::min( myStartPnt.Y(), myEndPnt.Y() );
461 QPoint topLeft = QPoint(left - pictureLeft, pictureTop - top );
462 QPoint bottomRight = QPoint(right - pictureLeft, pictureTop - bottom);
464 myRect = QRect(topLeft, bottomRight);
466 return (!myRect.isEmpty() && myRect.width() > 1);
469 //=================================================================================
470 // function : showImageSample()
471 // purpose : Display a preview of the image sample selected by the user
472 //=================================================================================
473 void EntityGUI_FeatureDetectorDlg::showImageSample()
475 // Cropp the image to the selection rectangle given by the user
476 aDetector->SetROI( myRect );
477 std::string samplePicturePath = aDetector->CroppImage();
479 // Display the result
480 QPixmap pixmap(QString(samplePicturePath.c_str()));
481 mySelectionGroup->FrameLabel->setPixmap(pixmap);
482 mySelectionGroup->FrameLabel->setMask(pixmap.mask());
485 //=================================================================================
486 // function : createOperation
488 //=================================================================================
489 GEOM::GEOM_IOperations_ptr EntityGUI_FeatureDetectorDlg::createOperation()
491 return myGeomGUI->GetGeomGen()->GetIShapesOperations( getStudyId() );
494 //=================================================================================
495 // function : execute()
497 //=================================================================================
498 bool EntityGUI_FeatureDetectorDlg::execute( ObjectList& objects )
502 GEOM::GEOM_IBasicOperations_var aBasicOperations = myGeomGUI->GetGeomGen()->GetIBasicOperations( getStudyId() );
503 GEOM::GEOM_IShapesOperations_var aShapesOperations = GEOM::GEOM_IShapesOperations::_narrow( getOperation() );
505 if (myConstructorId == CORNERS)
507 double subPictureLeft;
508 double subPictureTop;
509 if( !myRect.isEmpty() )
511 aDetector->SetROI( myRect );
512 subPictureLeft = myStartPnt.X();
513 subPictureTop = myStartPnt.Y();
517 subPictureLeft = pictureLeft;
518 subPictureTop = pictureTop;
520 aDetector->ComputeCorners();
521 CvPoint2D32f* corners = aDetector->GetCorners();
522 int cornerCount = aDetector->GetCornerCount();
525 // Build the geom objects associated to the detected corners and returned by execute
526 if( !aBasicOperations->_is_nil() && !aShapesOperations->_is_nil() )
528 GEOM::GEOM_Object_var aGeomCorner;
529 GEOM::ListOfGO_var geomCorners = new GEOM::ListOfGO();
530 geomCorners->length( cornerCount );
531 for (i = 0; i < cornerCount; i++)
533 double x = subPictureLeft + corners[i].x;
534 double y = subPictureTop - corners[i].y;
537 aGeomCorner = aBasicOperations->MakePointXYZ( x,y,z );
539 geomCorners[i] = aGeomCorner;
541 GEOM::GEOM_Object_var aCompound = aShapesOperations->MakeCompound(geomCorners);
542 if ( !aCompound->_is_nil() )
545 SALOMEDS::Color aColor;
550 aCompound->SetColor(aColor);
551 aCompound->SetMarkerStd(GEOM::MT_POINT,GEOM::MS_30);
552 objects.push_back( aCompound._retn() );
557 else if (myConstructorId == CONTOURS)
559 int method = 0 ; //CANNY
560 if( !myRect.isEmpty() && myRect.width() > 1 )
562 aDetector->SetROI( myRect );
563 method = 1 ; //COLORFILTER
566 GEOM::GEOM_ICurvesOperations_var aCurveOperations = myGeomGUI->GetGeomGen()->GetICurvesOperations( getStudyId() );
568 aDetector->ComputeContours( method );
569 std::vector< std::vector<cv::Point> > contours = aDetector->GetContours();
570 std::vector<cv::Vec4i> hierarchy = aDetector->GetContoursHierarchy();
572 std::vector< cv::Point > contour;
575 GEOM::ListOfGO_var geomContours = new GEOM::ListOfGO();
576 int contourCount = 0;
580 MESSAGE("hierarchy.size() =" << hierarchy.size())
581 for( ; idx >= 0; idx = hierarchy[idx][0])
583 // for(int count=0, child=idx; child>=0, count<1; child=hierarchy[idx][2], count++)
585 // contour = contours[child];
586 contour = contours[idx];
587 std::vector< cv::Point >::iterator it;
588 std::vector< cv::Point >::iterator it_previous;
589 std::vector< cv::Point >::iterator it_next;
590 GEOM::GEOM_Object_var aGeomContourPnt;
591 GEOM::ListOfGO_var geomContourPnts = new GEOM::ListOfGO();
593 geomContourPnts->length( contour.size() );
596 std::set< std::vector<int> > existing_points;
597 std::pair< std::set< std::vector<int> >::iterator,bool > pnt_it;
598 for ( it=contour.begin() ; it < contour.end(); it++ )
600 int pnt_array[] = {it->x,it->y};
601 std::vector<int> pnt (pnt_array, pnt_array + sizeof(pnt_array) / sizeof(int) );
603 pnt_it=existing_points.insert(pnt);
604 if (pnt_it.second == true) // To avoid double points in the contours
607 if (it!=contour.begin()) // From the second point on perform some checking to avoid loops in the contours we build
609 it_previous = boost::prior(it);
610 it_next = boost::next(it);
612 double u_v_scalar_product = (it->x - it_previous->x) * (it_next->x - it->x) +
613 (it->y - it_previous->y) * (it_next->y - it->y);
614 if (u_v_scalar_product < 0)
616 double u_v_det = (it->x - it_previous->x) * (it_next->y - it->y) -
617 (it->y - it_previous->y) * (it_next->x - it->x);
619 double norme_u = sqrt ( (it->x - it_previous->x)*(it->x - it_previous->x) +
620 (it->y - it_previous->y)*(it->y - it_previous->y) );
622 double norme_v = sqrt ( (it->x - it_next->x)*(it->x - it_next->x) +
623 (it->y - it_next->y)*(it->y - it_next->y) );
625 double u_v_sinus = u_v_det / (norme_u * norme_v);
627 if (fabs(u_v_sinus) < Precision::Confusion())
633 double x = -0.5 *width + it->x;
634 double y = 0.5 *height - it->y;
638 aGeomContourPnt = aBasicOperations->MakePointXYZ( x,y,z );
639 geomContourPnts->length( j+1 );
640 geomContourPnts[j] = aGeomContourPnt;
646 GEOM::GEOM_Object_var aWire;
647 if(myOutputGroup->RadioButton2->isChecked())
649 aWire = aCurveOperations->MakePolyline(geomContourPnts.in(), false);
651 else if(myOutputGroup->RadioButton1->isChecked())
653 aWire = aCurveOperations->MakeSplineInterpolation(geomContourPnts.in(), /*closed =*/ false, /*reordering =*/ false);
658 if ( !aWire->_is_nil() )
660 geomContours->length(contourCount + 1);
661 geomContours[contourCount] = aWire;
666 GEOM::GEOM_Object_var aContoursCompound = aShapesOperations->MakeCompound(geomContours);
667 if ( !aContoursCompound->_is_nil() )
669 objects.push_back( aContoursCompound._retn() );
674 // TEST not very conclusive
676 // else if(myConstructorId ==LINES)
678 // aDetector->ComputeLines();
679 // std::vector<cv::Vec4i> lines = aDetector->GetLines();
680 // GEOM::GEOM_Object_var Pnt1;
681 // GEOM::GEOM_Object_var Pnt2;
682 // GEOM::GEOM_Object_var aLine;
684 // GEOM::ListOfGO_var geomLines = new GEOM::ListOfGO();
686 // for( int i = 0; i < lines.size(); i++ )
688 // Pnt1 = aBasicOperations->MakePointXYZ( -0.5 *width + lines[i][0], 0.5 *height - lines[i][1], 0 );
689 // Pnt2 = aBasicOperations->MakePointXYZ( -0.5 *width + lines[i][2], 0.5 *height - lines[i][3], 0 );
690 // aLine = aBasicOperations->MakeLineTwoPnt( Pnt1, Pnt2 );
691 // if ( !aLine->_is_nil() )
693 // geomLines->length(linesCount + 1);
694 // geomLines[linesCount] = aLine;
698 // GEOM::GEOM_Object_var aLinesCompound = aShapesOperations->MakeCompound(geomLines);
699 // if ( !aLinesCompound->_is_nil() )
701 // objects.push_back( aLinesCompound._retn() );