Salome HOME
Fix for bos #16366 and bos #16182
[modules/geom.git] / src / EntityGUI / EntityGUI_FeatureDetectorDlg.cxx
1 // Copyright (C) 2007-2020  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
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, or (at your option) any later version.
10 //
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.
15 //
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
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 // GEOM GEOMGUI : GUI for Geometry component
24 // File   : EntityGUI_SketcherDlg.cxx
25 // Author : Renaud NEDELEC, Open CASCADE S.A.S.
26
27 // SALOME includes
28 #include "EntityGUI_FeatureDetectorDlg.h"
29 #include "ShapeRec_FeatureDetector.hxx"
30 #include "GEOM_Constants.h"
31
32 #include <OCCViewer_ViewWindow.h>
33 #include <OCCViewer_ViewManager.h>
34
35 #include <SOCC_ViewModel.h>
36
37 #include <DlgRef.h>
38 #include <GeometryGUI.h>
39 #include <EntityGUI.h>
40 #include <GEOMBase.h>
41
42 #include <SUIT_Desktop.h>
43 #include <SUIT_ResourceMgr.h>
44 #include <SUIT_Session.h>
45 #include <SUIT_ViewWindow.h>
46 #include <SalomeApp_Application.h>
47 #include <LightApp_Application.h>
48 #include <LightApp_SelectionMgr.h>
49
50 #include <SALOME_ListIO.hxx>
51
52 #include <SalomeApp_Study.h>
53
54 #include <Basics_OCCTVersion.hxx>
55
56 #include <utilities.h>
57 #include <Precision.hxx>
58
59 // OCCT includes
60 #include <gp_Pnt.hxx>
61 #include <TopoDS_Shape.hxx>
62 #include <TopoDS_Wire.hxx>
63
64 #include <BRepBuilderAPI_MakeVertex.hxx>
65 #include <BRepBuilderAPI_MakeFace.hxx>
66 #include <BRepBuilderAPI_MakePolygon.hxx>
67 #include <BRepBuilderAPI_Transform.hxx>
68
69 #include <AIS_Shape.hxx>
70
71 #include <TCollection_AsciiString.hxx>
72 //#include <StdSelect_DisplayMode.hxx>
73
74 #include <Graphic3d_MaterialAspect.hxx>
75
76 // C++ includes
77 #include <set>
78 #include <utility>
79
80 // boost includes
81 #include <boost/version.hpp>
82 #if BOOST_VERSION < 106700
83 #include <boost/utility.hpp>
84 #else
85 #include <boost/next_prior.hpp>
86 #endif
87
88 // Constructors
89 enum {
90   CONTOURS,
91   CORNERS,
92   LINES
93 };
94
95 enum {
96   KERNEL_SIZE,
97   FIND_CONTOURS_METHOD,
98   QUALITY_LEVEL,
99   MIN_DISTANCE,
100   TYPE_CRITERIA,
101   MAX_ITER,
102   EPSILON,
103   LOW_THRESHOLD,
104   RATIO,
105   L2GRADIENT,
106   SMOOTH_SIZE,
107   HBINS,
108   SBINS,
109   HIST_TYPE,
110   THRESHOLD_VALUE,
111   MAX_THRESHOLD,
112 };
113
114 // // // View
115 // // enum {
116 // //   XY,
117 // //   YZ,
118 // //   XZ
119 // // };
120   
121
122 //=================================================================================
123 // class    : EntityGUI_FeatureDetectorDlg()
124 // purpose  : Constructs a EntityGUI_FeatureDetectorDlg which is a child of 'parent', with the
125 //            name 'name' and widget flags set to 'f'.
126 //            The dialog will by default be modeless, unless you set 'modal' to
127 //            TRUE to construct a modal dialog.
128 //=================================================================================
129 EntityGUI_FeatureDetectorDlg::EntityGUI_FeatureDetectorDlg( GeometryGUI* theGeometryGUI, QWidget* parent,
130                                               bool modal, Qt::WindowFlags fl)
131   : GEOMBase_Skeleton(theGeometryGUI, parent, modal, fl) 
132 {
133   QPixmap image0(SUIT_Session::session()->resourceMgr()->loadPixmap("GEOM", tr("ICON_SELECT")));
134   QPixmap image1(SUIT_Session::session()->resourceMgr()->loadPixmap("OCCViewer", tr("ICON_OCCVIEWER_VIEW_DUMP")));
135
136   setWindowTitle(tr("GEOM_DETECT_TITLE"));
137   
138   /***************************************************************/
139   
140   mainFrame()->GroupConstructors->setTitle(tr("GEOM_FEATURES"));
141   mainFrame()->RadioButton1->setText(tr("GEOM_CONTOURS"));
142   mainFrame()->RadioButton2->setText(tr("GEOM_CORNERS"));
143   mainFrame()->RadioButton3->setAttribute(Qt::WA_DeleteOnClose);
144   mainFrame()->RadioButton3->close();
145   
146 //   myViewGroup = new DlgRef_3Radio(centralWidget());
147 //   myViewGroup->GroupBox1->setTitle(tr("GEOM_VIEW"));
148 //   myViewGroup->RadioButton1->setText(tr( "GEOM_TOP"  ));
149 //   myViewGroup->RadioButton2->setText(tr( "GEOM_FRONT"));
150 //   myViewGroup->RadioButton3->setText(tr( "GEOM_LEFT" ));
151 //   myViewButtonGroup = new QButtonGroup( this );
152 //   myViewButtonGroup->addButton( myViewGroup->RadioButton1, XY ); // Top view
153 //   myViewButtonGroup->addButton( myViewGroup->RadioButton2, YZ ); // Front View
154 //   myViewButtonGroup->addButton( myViewGroup->RadioButton3, XZ ); // Left View
155 //   
156 //   myViewGroup->hide();
157   
158   // Widgets for the selection of the picture and the Region Of Interest 
159   
160   
161   mySelectionGroup = new DlgRef_1Sel1Frame(centralWidget());
162
163   mySelectionGroup->PushButton1->setIcon(image0);
164   mySelectionGroup->PushButton1->setCheckable(true);
165   mySelectionGroup->PushButton1->setAutoExclusive(true);
166   
167   mySelectionGroup->PushButton2->setIcon(image1);
168   mySelectionGroup->PushButton2->setCheckable(true);
169   mySelectionGroup->PushButton2->setAutoExclusive(true);
170
171   mySelectionGroup->TextLabel1->setText(tr( "GEOM_PICTURE" ));
172   mySelectionGroup->FrameLabel->setText("");
173   
174   myOutputGroup = new DlgRef_3Radio(centralWidget());
175   myOutputGroup->GroupBox1->setTitle(tr("GEOM_DETECT_OUTPUT"));
176   myOutputGroup->RadioButton2->setText(tr( "GEOM_POLYLINE"  ));
177   myOutputGroup->RadioButton1->setText(tr( "GEOM_SPLINE"));
178   myOutputGroup->RadioButton3->hide();
179   
180 //   myOutputGroup->hide(); //caché pour la demo
181     
182   // Parameters 
183   QGridLayout* parametersLayout = new QGridLayout();
184   parametersLayout->setMargin(9);
185   QComboBox* kernelSize = new QComboBox();
186   kernelSize->addItems( QStringList() << "3" << "5" << "7" );
187   myWidgets.insert( KERNEL_SIZE, kernelSize );
188   myUseROI = new QCheckBox( tr("USE_ROI") );
189   myUseROI->setChecked( true );
190
191   parametersLayout->addWidget( new QLabel( tr("KERNEL_SIZE") ), 0, 0 );
192   parametersLayout->addWidget( kernelSize, 0, 1 );
193   parametersLayout->addWidget( myUseROI, 0, 2 );
194
195   // Corners Parameters 
196   myCornersParameters = new QFrame();
197   myCornersParameters->setFrameStyle(QFrame::NoFrame);
198   QDoubleSpinBox* qualityLevel = new QDoubleSpinBox();
199   qualityLevel->setValue( 0.2 );
200   qualityLevel->setSingleStep( 0.1 );
201   qualityLevel->setRange( 0.01, 0.99 );
202   myWidgets.insert( QUALITY_LEVEL, qualityLevel );
203   QDoubleSpinBox* minDistance = new QDoubleSpinBox();
204   minDistance->setValue( 1 );
205   myWidgets.insert( MIN_DISTANCE, minDistance );
206   QComboBox* typeCriteria = new QComboBox();
207   typeCriteria->addItems( QStringList() << tr("CV_TERMCRIT_ITER") << tr("CV_TERMCRIT_EPS") << tr("CV_TERMCRIT_ITER | CV_TERMCRIT_EPS") );
208   typeCriteria->setCurrentIndex( 2 );
209   myWidgets.insert( TYPE_CRITERIA, typeCriteria );
210   QSpinBox* maxIter = new QSpinBox();
211   maxIter->setValue( 20 );
212   maxIter->setRange( 1, 100 );
213   myWidgets.insert( MAX_ITER, maxIter );
214   QDoubleSpinBox* epsilon = new QDoubleSpinBox();
215   epsilon->setValue( 0.03 );
216   epsilon->setSingleStep( 0.01 );
217   myWidgets.insert( EPSILON, epsilon );
218
219   QGridLayout* cornersLayout = new QGridLayout();
220   cornersLayout->setMargin( 0 );
221   cornersLayout->addWidget( new QLabel( tr("QUALITY_LEVEL") ), 0, 0 );
222   cornersLayout->addWidget( qualityLevel, 0, 1 );
223   cornersLayout->addWidget( new QLabel( tr("MIN_DISTANCE") ), 0, 2 );
224   cornersLayout->addWidget( minDistance, 0 ,3 );
225   cornersLayout->addWidget( new QLabel( tr("TYPE_CRITERIA") ), 1, 0 );
226   cornersLayout->addWidget( typeCriteria, 1, 1, 1, 3 );
227   cornersLayout->addWidget( new QLabel( tr("MAX_ITER") ), 2, 0 );
228   cornersLayout->addWidget( maxIter, 2, 1 );
229   cornersLayout->addWidget( new QLabel( tr("EPSILON") ), 2, 2 );
230   cornersLayout->addWidget( epsilon, 2 , 3 );
231
232   myCornersParameters->setLayout( cornersLayout );
233
234   // Contours Parameters
235   myContoursParameters = new QFrame();
236   myContoursParameters->setFrameStyle(QFrame::NoFrame);
237
238   QComboBox* findContoursMethod = new QComboBox();
239   findContoursMethod->addItems( QStringList() << tr("CV_CHAIN_APPROX_NONE") << tr("CV_CHAIN_APPROX_SIMPLE") << tr("CV_CHAIN_APPROX_TC89_L1") << tr("CV_CHAIN_APPROX_TC89_KCOS") );
240   myWidgets.insert( FIND_CONTOURS_METHOD, findContoursMethod );
241
242   myCannyParameters = new QFrame();
243   myCannyParameters->setFrameStyle(QFrame::NoFrame);
244   QSpinBox* threshold = new QSpinBox();
245   threshold->setRange( 0, 255 );
246   threshold->setValue( 100 );
247   myWidgets.insert( LOW_THRESHOLD, threshold );
248   QSpinBox* ratio = new QSpinBox();
249   ratio->setValue( 3 );
250   ratio->setRange( 0, 255 );
251   myWidgets.insert( RATIO, ratio );
252   QCheckBox* L2gradient = new QCheckBox(tr("L2GRADIENT"));
253   L2gradient->setChecked(true);
254   myWidgets.insert( L2GRADIENT, L2gradient );
255
256   QGridLayout* cannyLayout = new QGridLayout();
257   cannyLayout->setMargin( 0 );
258   cannyLayout->addWidget( new QLabel( tr("LOWTHRESHOLD") ), 0, 0 );
259   cannyLayout->addWidget( threshold, 0, 1 );
260   cannyLayout->addWidget( new QLabel( tr("RATIO") ), 0, 2 );
261   cannyLayout->addWidget( ratio, 0, 3 );
262   cannyLayout->addWidget( L2gradient, 1, 0 );
263
264   myCannyParameters->setLayout( cannyLayout );
265   myCannyParameters->setHidden( true );
266
267   myColorFilterParameters = new QFrame();
268   myColorFilterParameters->setFrameStyle(QFrame::NoFrame);
269
270   QSpinBox* smoothSize = new QSpinBox();
271   smoothSize->setValue( 3 );
272   smoothSize->setSingleStep( 2 );
273   smoothSize->setRange( 1, 1000 );
274   myWidgets.insert( SMOOTH_SIZE, smoothSize );
275   QSpinBox* hbins = new QSpinBox();
276   hbins->setValue( 30 );
277   hbins->setRange( 0, 179 );
278   myWidgets.insert( HBINS, hbins );
279   QSpinBox* sbins = new QSpinBox();
280   sbins->setValue( 32 );
281   sbins->setRange( 0, 255 );
282   myWidgets.insert( SBINS, sbins );
283   QComboBox* histType = new QComboBox();
284   histType->addItems( QStringList() << tr("CV_HIST_ARRAY") << tr("CV_HIST_SPARSE") );
285   myWidgets.insert( HIST_TYPE, histType );
286   QDoubleSpinBox* thresholdValue = new QDoubleSpinBox();
287   thresholdValue->setRange( 0, 254 );
288   // 1 is a good default value for the threshold. It means that we are very permissive
289   // about what will be considered INSIDE the zone we want to find the frontier of
290   // This makes the algorithm more robust against a bit inhomogeneous parts in the zone
291   // that we want to delimitate.
292   // The drawback is if we want to delimitate a zone which color is very similar to the zone
293   // we consider as the OUTSIDE, the result will be bad.
294   // The current use cases are more of the first form : 
295   //  - Strongly contrasted INSIDE and OUTSIDE zones
296   //  - Small inhomogenities in each zone
297   thresholdValue->setValue( 1 );
298   myWidgets.insert( THRESHOLD_VALUE, thresholdValue );
299   QDoubleSpinBox* maxThreshold = new QDoubleSpinBox();
300   maxThreshold->setRange( 1, 255 );
301   maxThreshold->setValue( 255 );
302   myWidgets.insert( MAX_THRESHOLD, maxThreshold );
303
304   QGridLayout* colorFilterLayout = new QGridLayout();
305   colorFilterLayout->setMargin( 0 );
306   colorFilterLayout->addWidget( new QLabel( tr("SMOOTH_SIZE") ), 0, 0 );
307   colorFilterLayout->addWidget( smoothSize, 0, 1 );
308   colorFilterLayout->addWidget( new QLabel( tr("HBINS") ), 1, 0 );
309   colorFilterLayout->addWidget( hbins, 1, 1 );
310   colorFilterLayout->addWidget( new QLabel( tr("SBINS") ), 1, 2 );
311   colorFilterLayout->addWidget( sbins, 1, 3 );
312   colorFilterLayout->addWidget( new QLabel( tr("HIST_TYPE") ), 2, 0 );
313   colorFilterLayout->addWidget( histType, 2, 1, 1, 3 );
314   colorFilterLayout->addWidget( new QLabel( tr("THRESHOLD_VALUE") ), 3, 0 );
315   colorFilterLayout->addWidget( thresholdValue, 3, 1 );
316   colorFilterLayout->addWidget( new QLabel( tr("MAX_THRESHOLD") ), 3, 2 );
317   colorFilterLayout->addWidget( maxThreshold, 3, 3 );
318
319   myColorFilterParameters->setLayout( colorFilterLayout );
320   QGridLayout* contoursLayout = new QGridLayout();
321   contoursLayout->setMargin( 0 );
322   contoursLayout->addWidget( new QLabel( tr("FIND_CONTOURS_METHOD") ), 0, 0 );
323   contoursLayout->addWidget( findContoursMethod, 0, 1 );
324   contoursLayout->addWidget( myCannyParameters, 1, 0, 1, 3 );
325   contoursLayout->addWidget( myColorFilterParameters, 1, 0, 1, 3  );
326
327   myContoursParameters->setLayout( contoursLayout );
328
329   parametersLayout->addWidget( myCornersParameters, 1, 0, 1, 3 );
330   parametersLayout->addWidget( myContoursParameters, 1, 0, 1, 3 );
331
332   QVBoxLayout* layout = new QVBoxLayout(centralWidget());
333   layout->setMargin(0); layout->setSpacing(6);
334 //   layout->addWidget( myViewGroup);
335   layout->addLayout( parametersLayout );
336   layout->addWidget( mySelectionGroup);
337   layout->addWidget( myOutputGroup);
338   
339 //   mainFrame()->GroupBoxName->hide();
340   
341   // Build an instance of detection used to perform image processing operations
342   myDetector = new ShapeRec_FeatureDetector();
343   
344   setHelpFileName( "shape_recognition_page.html" );
345   
346   Init();
347   
348 }
349
350 //=================================================================================
351 // function : ~EntityGUI_FeatureDetectorDlg()
352 // purpose  : Destroys the object and frees any allocated resources
353 //=================================================================================
354 EntityGUI_FeatureDetectorDlg::~EntityGUI_FeatureDetectorDlg()
355 {
356   delete myDetector;
357 }
358
359 //=================================================================================
360 // function : Init()
361 // purpose  :
362 //=================================================================================
363 void EntityGUI_FeatureDetectorDlg::Init()
364 {
365   connect( myGeomGUI,         SIGNAL( SignalCloseAllDialogs() ), this, SLOT( ClickOnCancel() ) );
366   connect( buttonOk(),        SIGNAL( clicked() ),               this, SLOT( ClickOnOk() ) );
367   connect( buttonApply(),     SIGNAL( clicked() ),               this, SLOT( ClickOnApply() ) );
368   connect( myUseROI,          SIGNAL( toggled(bool) ),           this, SLOT( onCheckBoxClicked(bool) ) );
369   connect( this,              SIGNAL(constructorsClicked(int)),  this, SLOT(ConstructorsClicked(int))); 
370   connect( mySelectionGroup->PushButton2,      SIGNAL( clicked() ),               this, SLOT( onButtonClicked() ) );
371   connect( mySelectionGroup->PushButton1,       SIGNAL( clicked() ),               this, SLOT( onButtonClicked() ) );  
372 //   connect( myViewButtonGroup, SIGNAL( buttonClicked( int ) ),    this, SLOT( onViewClicked( int ) ) );
373   connect( myGeomGUI->getApp()->selectionMgr(), SIGNAL( currentSelectionChanged() ),this, SLOT( SelectionIntoArgument() ) );
374   
375   myConstructorId = 0;
376   mySelectionGroup->PushButton1->click();
377   
378 //   SetEditCurrentArgument();
379   SelectionIntoArgument();
380   
381   initName(tr("GEOM_CONTOURS")); 
382   resize(100,100);
383   
384 //   myViewGroup->RadioButton1->setChecked(true);
385   myOutputGroup->RadioButton1->setChecked(true);
386   
387   gp_Pnt aOrigin = gp_Pnt(0, 0, 0);
388   gp_Dir aDirZ = gp_Dir(0, 0, 1);
389   gp_Dir aDirX = gp_Dir(1, 0, 0);
390   
391   aGlobalCS = gp_Ax3(aOrigin, aDirZ, aDirX);
392   
393   myStartPnt = gp_Pnt(0,0,0);
394   myEndPnt = myStartPnt;
395   
396   myGeomGUI->SetWorkingPlane( aGlobalCS );
397   myGeomGUI->ActiveWorkingPlane();
398   
399   ConstructorsClicked(myConstructorId);
400 }
401
402 //=================================================================================
403 // function : SelectionIntoArgument()
404 // purpose  : Called when selection as changed or other case
405 //=================================================================================
406 void EntityGUI_FeatureDetectorDlg::SelectionIntoArgument()
407 {
408   
409   // TODO supprimer les lignes qui ne servent Ã  rien le cas Ã©chéant
410   SUIT_ViewWindow*       theViewWindow  = getDesktop()->activeWindow();
411   SOCC_Viewer* soccViewer = (SOCC_Viewer*)(theViewWindow->getViewManager()->getViewModel());
412
413   if (!myEditCurrentArgument->isEnabled())
414     return;
415   
416   myEditCurrentArgument->setText( "" );
417
418   LightApp_SelectionMgr* aSelMgr = myGeomGUI->getApp()->selectionMgr();
419   SALOME_ListIO aSelList;
420   aSelMgr->selectedObjects(aSelList);
421   SALOME_ListIteratorOfListIO anIt( aSelList );
422   
423   for( ; anIt.More(); anIt.Next() )
424     if( !anIt.Value().IsNull() )
425     {
426       myFaceEntry = anIt.Value()->getEntry();
427     }
428
429   if (aSelList.Extent() != 1) {
430     if (myEditCurrentArgument == mySelectionGroup->LineEdit1) 
431       myFace.nullify();
432     return;
433   }
434
435   TopAbs_ShapeEnum aNeedType = TopAbs_FACE ;
436   GEOM::GeomObjPtr aSelectedObject = getSelected( aNeedType );
437   TopoDS_Shape aShape;
438   if ( aSelectedObject && GEOMBase::GetShape( aSelectedObject.get(), aShape ) && !aShape.IsNull() ) {
439     QString aName = GEOMBase::GetName( aSelectedObject.get() );
440     myEditCurrentArgument->setText( aName );
441     
442     if ( myEditCurrentArgument == mySelectionGroup->LineEdit1 ) {
443       myFace = aSelectedObject;
444
445       SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( SUIT_Session::session()->activeApplication()->activeStudy() );
446       if ( !study ) return;
447       LightApp_Application* app = ::qobject_cast<LightApp_Application*>( study->application() );
448       if ( !app ) return;
449       SUIT_ViewManager* vm = app->activeViewManager();
450       if ( !vm ) return;
451       PropMap propMap = study->getObjectProperties( vm->getGlobalId(), myFaceEntry );
452       QString theImgFileName = propMap.value( GEOM::propertyName( GEOM::Texture ) ).toString();
453       if ( theImgFileName.isEmpty() )
454         return;
455
456       // Setting the image caracteristics
457       myDetector->SetPath( theImgFileName.toStdString() );
458       height            =  myDetector->GetImgHeight();
459       width             =  myDetector->GetImgWidth();
460       pictureLeft       = -0.5 * width;              // X coordinate of the top left corner of the background image in the view
461       pictureTop        =  0.5 * height;             // Y coordinate of both top corners
462       
463     } 
464   }
465   
466 }
467
468 //=================================================================================
469 // function : acceptMouseEvent()
470 // purpose  :
471 //=================================================================================
472 bool EntityGUI_FeatureDetectorDlg::acceptMouseEvent() const
473
474   return mySelectionGroup->PushButton2->isChecked();  
475 }
476
477 //=======================================================================
478 // function : ClickOnOk()
479 // purpose  :
480 //=======================================================================
481 void EntityGUI_FeatureDetectorDlg::ClickOnOk()
482 {
483   setIsApplyAndClose( true );
484   if (onAccept())
485     ClickOnCancel();
486 }
487
488 //=================================================================================
489 // function : ClickOnApply()
490 // purpose  :
491 //=================================================================================
492 bool EntityGUI_FeatureDetectorDlg::ClickOnApply()
493 {
494   if (!onAccept())
495     return false;
496
497 //   initName();
498   ConstructorsClicked(getConstructorId());
499   return true;
500 }
501
502 //=================================================================================
503 // function : onConstructorClicked(int)
504 // purpose  :
505 //=================================================================================
506 void EntityGUI_FeatureDetectorDlg::ConstructorsClicked(int id)
507 {
508   MESSAGE("Constructor id ="<<id)
509   myConstructorId = id;
510   switch (id)
511   {
512     case CORNERS:
513       myCornersParameters->show();
514       myContoursParameters->hide();
515 //       myViewGroup->show();
516 //       mySelectionGroup->show();
517       myOutputGroup->hide();
518 //       mySelectionGroup->TextLabel2->setText(tr("GEOM_DETECT_ZONE"));
519       initName(tr("GEOM_CORNERS"));
520       break;
521     case CONTOURS:
522       myCornersParameters->hide();
523       myContoursParameters->show();
524 //       myViewGroup->hide();
525 //       mySelectionGroup->hide();
526 //       mySelectionGroup->show();
527       myOutputGroup->show();
528       mySelectionGroup->TextLabel2->setText(tr("GEOM_COLOR_FILTER"));
529       initName(tr("GEOM_CONTOURS"));
530       break;
531     case LINES:
532 //       myViewGroup->hide();
533 //       mySelectionGroup->hide();
534 //       mySelectionGroup->show();
535       myOutputGroup->hide();
536       mySelectionGroup->TextLabel2->setText(tr(""));
537       initName(tr("GEOM_LINES"));
538       break;
539   }
540 }
541
542 // //=================================================================================
543 // // function : onViewClicked()
544 // // purpose  :
545 // //=================================================================================
546 // void EntityGUI_FeatureDetectorDlg::onViewClicked(int id)
547 // {
548 //   gp_Pnt aOrigin = gp_Pnt(0, 0, 0);
549 //   gp_Dir aDirZ;
550 //   gp_Dir aDirX;
551 //   
552 //   switch(id)
553 //   {
554 //     case XY:
555 //         aDirZ = gp_Dir(0, 0, 1);
556 //         aDirX = gp_Dir(1, 0, 0);
557 //       break;
558 //     case YZ:
559 //         aDirZ = gp_Dir(1, 0, 0);
560 //         aDirX = gp_Dir(0, 1, 0);
561 //       break;
562 //     case XZ:
563 //         aDirZ = gp_Dir(0, -1, 0);
564 //         aDirX = gp_Dir(1, 0 , 0);
565 //       break;
566 //   }
567 //   
568 //   myWPlane = gp_Ax3(aOrigin, aDirZ, aDirX);
569 //   myGeomGUI->SetWorkingPlane( myWPlane );
570 //   myGeomGUI->ActiveWorkingPlane();
571 //   
572 // }
573
574 //=================================================================================
575 // function : onButtonClicked()
576 // purpose  :
577 //=================================================================================
578 void EntityGUI_FeatureDetectorDlg::onButtonClicked()
579 {
580   QPushButton* send = (QPushButton*)sender();
581   if (send == mySelectionGroup->PushButton2)
582   {
583     mySelectionGroup->LineEdit1->setEnabled(false);
584   }
585   else if (send == mySelectionGroup->PushButton1)
586   {
587     myStartPnt = gp_Pnt(0,0,0);
588     myEndPnt   = myStartPnt;
589     myEditCurrentArgument = mySelectionGroup->LineEdit1;
590     mySelectionGroup->LineEdit1->setEnabled(true);   
591   }
592 }
593
594 //=================================================================================
595 // function : onCheckBoxClicked(bool)
596 // purpose  :
597 //=================================================================================
598 void EntityGUI_FeatureDetectorDlg::onCheckBoxClicked( bool isChecked )
599 {
600   mySelectionGroup->TextLabel2->setVisible( isChecked );
601   mySelectionGroup->Frame->setVisible( isChecked );
602   mySelectionGroup->PushButton2->setVisible( isChecked );
603   myCannyParameters->setHidden( isChecked );
604   myColorFilterParameters->setHidden( !isChecked );
605 }
606
607 //=================================================================================
608 // function : parametersChanged()
609 // purpose  :
610 //=================================================================================
611 ShapeRec_Parameters* EntityGUI_FeatureDetectorDlg::parametersChanged()
612 {
613   ShapeRec_Parameters* aParameters = new ShapeRec_Parameters();
614
615   if ( myConstructorId == CORNERS ) {
616     ShapeRec_CornersParameters* aCornersParameters = dynamic_cast<ShapeRec_CornersParameters*>( aParameters );
617     if ( !aCornersParameters ) aCornersParameters = new ShapeRec_CornersParameters();
618     aCornersParameters->qualityLevel = (dynamic_cast<QDoubleSpinBox*>(myWidgets[QUALITY_LEVEL]))->value();
619     aCornersParameters->minDistance  = (dynamic_cast<QDoubleSpinBox*>(myWidgets[MIN_DISTANCE]))->value();
620     switch ( (dynamic_cast<QComboBox*>(myWidgets[TYPE_CRITERIA]))->currentIndex() ) {
621     case 0: aCornersParameters->typeCriteria = CV_TERMCRIT_ITER;
622     case 1: aCornersParameters->typeCriteria = CV_TERMCRIT_EPS;
623     case 2: aCornersParameters->typeCriteria = CV_TERMCRIT_ITER | CV_TERMCRIT_EPS;
624     }
625     aCornersParameters->maxIter = (dynamic_cast<QSpinBox*>(myWidgets[MAX_ITER]))->value();
626     aCornersParameters->epsilon = (dynamic_cast<QDoubleSpinBox*>(myWidgets[EPSILON]))->value();
627     aParameters = aCornersParameters;
628   }
629   else if ( myConstructorId == CONTOURS ) {
630     if ( !myUseROI->isChecked() ) { 
631       ShapeRec_CannyParameters* aCannyParameters = dynamic_cast<ShapeRec_CannyParameters*>( aParameters );
632       if ( !aCannyParameters ) aCannyParameters = new ShapeRec_CannyParameters();
633       aCannyParameters->lowThreshold = (dynamic_cast<QSpinBox*>(myWidgets[LOW_THRESHOLD]))->value();
634       aCannyParameters->ratio        = (dynamic_cast<QSpinBox*>(myWidgets[RATIO]))->value();
635       aCannyParameters->L2gradient   = (dynamic_cast<QCheckBox*>(myWidgets[L2GRADIENT]))->isChecked();
636       aParameters = aCannyParameters;
637     }
638     else {
639       ShapeRec_ColorFilterParameters* aColorFilterParameters = dynamic_cast<ShapeRec_ColorFilterParameters*>( aParameters );
640       if ( !aColorFilterParameters ) aColorFilterParameters = new ShapeRec_ColorFilterParameters();
641       int aSmoothSize = (dynamic_cast<QSpinBox*>(myWidgets[SMOOTH_SIZE]))->value();
642       aColorFilterParameters->smoothSize  = aSmoothSize % 2 == 0 ? aSmoothSize - 1 : aSmoothSize;
643       aColorFilterParameters->histSize[0] = (dynamic_cast<QSpinBox*>(myWidgets[HBINS]))->value();
644       aColorFilterParameters->histSize[1] = (dynamic_cast<QSpinBox*>(myWidgets[SBINS]))->value();
645       switch ( (dynamic_cast<QComboBox*>(myWidgets[HIST_TYPE]))->currentIndex() ) {
646       case 0: aColorFilterParameters->histType = CV_HIST_ARRAY;  break;
647       case 1: aColorFilterParameters->histType = CV_HIST_SPARSE; break;
648       }
649       aColorFilterParameters->threshold    = (dynamic_cast<QDoubleSpinBox*>(myWidgets[THRESHOLD_VALUE]))->value();
650       aColorFilterParameters->maxThreshold = (dynamic_cast<QDoubleSpinBox*>(myWidgets[MAX_THRESHOLD]))->value();
651       aParameters = aColorFilterParameters;
652     }
653   }
654  
655   aParameters->kernelSize = ( (dynamic_cast<QComboBox*>(myWidgets[KERNEL_SIZE]))->currentText() ).toInt();
656   switch ( (dynamic_cast<QComboBox*>(myWidgets[FIND_CONTOURS_METHOD]))->currentIndex() ) {
657   case 0: aParameters->findContoursMethod = CV_CHAIN_APPROX_NONE;      break;
658   case 1: aParameters->findContoursMethod = CV_CHAIN_APPROX_SIMPLE;    break;
659   case 2: aParameters->findContoursMethod = CV_CHAIN_APPROX_TC89_L1;   break;
660   case 3: aParameters->findContoursMethod = CV_CHAIN_APPROX_TC89_KCOS; break;
661   }
662
663   return aParameters;
664 }
665
666 //=================================================================================
667 // function : setStartPnt( const QPoint& )
668 // purpose  :
669 //=================================================================================
670 void EntityGUI_FeatureDetectorDlg::setStartPnt(const gp_Pnt& theStartPnt)
671 {
672   myStartPnt = theStartPnt;
673   MESSAGE("myStartPnt = ("<<theStartPnt.X()<<", "<<theStartPnt.Y()<<")")
674 }
675
676 //=================================================================================
677 // function : setEndPnt( const QPoint& )
678 // purpose  :
679 //=================================================================================
680 void EntityGUI_FeatureDetectorDlg::setEndPnt(const gp_Pnt& theEndPnt)
681 {
682   myEndPnt = theEndPnt;
683   MESSAGE("myEndPnt = ("<<theEndPnt.X()<<", "<<theEndPnt.Y()<<")")
684   if (setSelectionRect() && myDetector->GetImgHeight() > 0)
685     showImageSample();
686 }
687
688 //=================================================================================
689 // function : setSelectionRect()
690 // purpose  :
691 //=================================================================================
692 bool EntityGUI_FeatureDetectorDlg::setSelectionRect()
693
694   // Set detection rectangle in the background image coordinates system
695   double left    = std::min( myStartPnt.X(), myEndPnt.X() );
696   double top     = std::max( myStartPnt.Y(), myEndPnt.Y() );
697   double right   = std::max( myStartPnt.X(), myEndPnt.X() );
698   double bottom  = std::min( myStartPnt.Y(), myEndPnt.Y() );
699   
700   QPoint topLeft     = QPoint(left  - pictureLeft, pictureTop - top   );
701   QPoint bottomRight = QPoint(right - pictureLeft, pictureTop - bottom);
702   
703   myRect = QRect(topLeft, bottomRight);
704   
705   return (!myRect.isEmpty() && myRect.width() > 1);
706 }
707
708 //=================================================================================
709 // function : showImageSample()
710 // purpose  : Display a preview of the image sample selected by the user
711 //=================================================================================
712 void EntityGUI_FeatureDetectorDlg::showImageSample()
713
714   // Cropp the image to the selection rectangle given by the user
715   myDetector->SetROI( myRect ); 
716   std::string samplePicturePath = myDetector->CroppImage();
717   
718   // Display the result
719   QPixmap pixmap(QString(samplePicturePath.c_str()));
720   mySelectionGroup->FrameLabel->setPixmap(pixmap);
721   mySelectionGroup->FrameLabel->setMask(pixmap.mask());
722 }
723
724 //=================================================================================
725 // function : createOperation
726 // purpose  :
727 //=================================================================================
728 GEOM::GEOM_IOperations_ptr EntityGUI_FeatureDetectorDlg::createOperation()
729 {
730   return myGeomGUI->GetGeomGen()->GetIShapesOperations();
731 }
732
733 //=================================================================================
734 // function : execute()
735 // purpose  :
736 //=================================================================================
737 bool EntityGUI_FeatureDetectorDlg::execute( ObjectList& objects )
738 {
739   bool res = false;
740   
741   GEOM::GEOM_IBasicOperations_var  aBasicOperations  = myGeomGUI->GetGeomGen()->GetIBasicOperations();
742   GEOM::GEOM_IShapesOperations_var aShapesOperations = GEOM::GEOM_IShapesOperations::_narrow( getOperation() );
743
744   ShapeRec_Parameters* parameters = parametersChanged();
745   if ( !parameters ) parameters = new ShapeRec_Parameters();
746
747   bool useROI = myUseROI->isChecked() && !myRect.isEmpty();
748   try {
749     if (myConstructorId == CORNERS)
750     {
751       double subPictureLeft;
752       double subPictureTop;
753       if( useROI )
754       {
755         subPictureLeft    = myStartPnt.X();                
756         subPictureTop     = myStartPnt.Y();
757       }
758       else
759       {
760         subPictureLeft    = pictureLeft;
761         subPictureTop     = pictureTop;
762       }
763       myDetector->ComputeCorners( useROI, parameters );
764       CvPoint2D32f* corners     = myDetector->GetCorners();
765       int cornerCount           = myDetector->GetCornerCount();
766       int i;
767     
768       // Build the geom objects associated to the detected corners and returned by execute   
769       if( !aBasicOperations->_is_nil() && !aShapesOperations->_is_nil() ) 
770       {
771         GEOM::GEOM_Object_var  aGeomCorner;
772         GEOM::ListOfGO_var     geomCorners = new GEOM::ListOfGO();
773         geomCorners->length( cornerCount );
774         for (i = 0; i < cornerCount; i++)
775         {
776           double x = subPictureLeft + corners[i].x;
777           double y = subPictureTop  - corners[i].y;
778           double z =  0;
779         
780           aGeomCorner = aBasicOperations->MakePointXYZ( x,y,z );
781         
782           geomCorners[i] = aGeomCorner;  
783         } 
784         GEOM::GEOM_Object_var aCompound = aShapesOperations->MakeCompound(geomCorners);    
785         if ( !aCompound->_is_nil() )
786         {
787           // Dark blue color
788           SALOMEDS::Color aColor;
789           aColor.R = 0;
790           aColor.G = 0;
791           aColor.B = 0.8;
792
793           aCompound->SetColor(aColor);
794           aCompound->SetMarkerStd(GEOM::MT_POINT,GEOM::MS_30);
795           objects.push_back( aCompound._retn() );
796           res = true;
797         }
798       }   
799     }
800     else if (myConstructorId == CONTOURS)
801     {    
802       GEOM::GEOM_ICurvesOperations_var aCurveOperations = myGeomGUI->GetGeomGen()->GetICurvesOperations();
803
804       myDetector->ComputeContours( useROI, parameters );
805       std::vector< std::vector<cv::Point> >   contours  = myDetector->GetContours();
806       std::vector<cv::Vec4i>                  hierarchy = myDetector->GetContoursHierarchy();
807     
808       std::vector< cv::Point >                contour;
809       int idx = 0;
810       
811       GEOM::ListOfGO_var                      geomContours = new GEOM::ListOfGO();
812       int contourCount = 0;
813     
814       bool insert;
815     
816       MESSAGE("hierarchy.size() =" << hierarchy.size()) 
817       if ( hierarchy.size() < 1 ) {
818         getOperation()->SetErrorCode( "Impossible detected contours" );
819         return false;
820       }
821
822       for( ; idx >= 0; idx = hierarchy[idx][0])
823       {
824 //       for(int count=0, child=idx; child>=0, count<1; child=hierarchy[idx][2], count++)
825 //       {     
826 //         contour = contours[child];
827         contour = contours[idx];
828         std::vector< cv::Point >::iterator it;
829         std::vector< cv::Point >::iterator it_previous;
830         std::vector< cv::Point >::iterator it_next;
831         GEOM::GEOM_Object_var  aGeomContourPnt;
832         GEOM::ListOfGO_var     geomContourPnts = new GEOM::ListOfGO();
833        
834         geomContourPnts->length( contour.size() );
835
836         int j = 0;
837         std::set< std::vector<int> > existing_points;
838         std::pair< std::set< std::vector<int> >::iterator,bool > pnt_it;
839         for ( it=contour.begin() ; it < contour.end()-1; it++ )
840         {
841           int pnt_array[] = {it->x,it->y};     
842           std::vector<int> pnt (pnt_array, pnt_array + sizeof(pnt_array) / sizeof(int) );
843
844           pnt_it=existing_points.insert(pnt);
845           if (pnt_it.second == true)         // To avoid double points in the contours
846           {
847             insert = true;
848             if (it!=contour.begin())         // From the second point on perform some checking to avoid loops in the contours we build
849             {
850               it_previous = boost::prior(it);
851               it_next = boost::next(it);
852               
853               double u_v_scalar_product = (it->x - it_previous->x) * (it_next->x - it->x) + 
854                                           (it->y - it_previous->y) * (it_next->y - it->y);                                       
855               if (u_v_scalar_product < 0)
856               {
857                 double u_v_det = (it->x - it_previous->x) * (it_next->y - it->y) - 
858                                  (it->y - it_previous->y) * (it_next->x - it->x);
859                                           
860                 double norme_u = sqrt ( double(it->x - it_previous->x) * double(it->x - it_previous->x) +
861                                         double(it->y - it_previous->y) * double(it->y - it_previous->y) );
862                 
863                 double norme_v = sqrt ( double(it->x - it_next->x) * double(it->x - it_next->x) +
864                                         double(it->y - it_next->y) * double(it->y - it_next->y) );
865                                                                                                 
866                 double u_v_sinus = u_v_det / (norme_u * norme_v);
867                 
868                 if (fabs(u_v_sinus) < Precision::Confusion())
869                 { 
870                   insert = false;
871                 }                         
872               }
873             }
874             double x = -0.5 *width  + it->x;
875             double y =  0.5 *height - it->y;
876             double z =  0;
877             if (insert)
878             {
879               aGeomContourPnt    = aBasicOperations->MakePointXYZ( x,y,z );
880               geomContourPnts->length( j+1 );
881               geomContourPnts[j] = aGeomContourPnt;
882               j++;
883             }
884           }
885         }
886         
887         GEOM::GEOM_Object_var aWire;
888         if(myOutputGroup->RadioButton2->isChecked())
889         {
890           aWire = aCurveOperations->MakePolyline(geomContourPnts.in(), false);
891         }
892         else if(myOutputGroup->RadioButton1->isChecked())
893         {
894           aWire = aCurveOperations->MakeSplineInterpolation(geomContourPnts.in(), /*closed =*/ false, /*reordering =*/ false);
895         }
896         else
897           return res;
898         
899         if ( !aWire->_is_nil() )
900         {
901           geomContours->length(contourCount + 1);
902           geomContours[contourCount] = aWire;
903           contourCount++;
904         }
905 //       }
906       }
907       GEOM::GEOM_Object_var aContoursCompound = aShapesOperations->MakeCompound(geomContours);
908       if ( !aContoursCompound->_is_nil() )
909       {
910         objects.push_back( aContoursCompound._retn() );
911       }
912       res=true;
913     }
914   }
915   catch( ... ) {
916     getOperation()->SetErrorCode( "Impossible detected contours/corners" );
917     return false;
918   }
919   
920   // TEST not very conclusive
921   
922 //   else if(myConstructorId ==LINES)
923 //   {
924 //     myDetector->ComputeLines();
925 //     std::vector<cv::Vec4i>  lines = myDetector->GetLines();
926 //     GEOM::GEOM_Object_var  Pnt1;
927 //     GEOM::GEOM_Object_var  Pnt2;
928 //     GEOM::GEOM_Object_var  aLine;
929 //     
930 //     GEOM::ListOfGO_var     geomLines = new GEOM::ListOfGO();
931 //     int linesCount=0;
932 //     for( int i = 0; i < lines.size(); i++ )
933 //     {
934 //       Pnt1 = aBasicOperations->MakePointXYZ( -0.5 *width + lines[i][0], 0.5 *height - lines[i][1], 0 );
935 //       Pnt2 = aBasicOperations->MakePointXYZ( -0.5 *width + lines[i][2], 0.5 *height - lines[i][3], 0 );
936 //       aLine = aBasicOperations->MakeLineTwoPnt( Pnt1, Pnt2 );
937 //       if ( !aLine->_is_nil() )
938 //       {
939 //         geomLines->length(linesCount + 1);
940 //         geomLines[linesCount] = aLine;
941 //         linesCount++;
942 //       }
943 //     }
944 //     GEOM::GEOM_Object_var aLinesCompound = aShapesOperations->MakeCompound(geomLines);
945 //     if ( !aLinesCompound->_is_nil() )
946 //     {
947 //       objects.push_back( aLinesCompound._retn() );
948 //     }
949 // 
950 //     res=true;
951 //   }
952   
953   return res;
954 }
955
956 //=================================================================================
957 // function : getSourceObjects
958 // purpose  : virtual method to get source objects
959 //=================================================================================
960 QList<GEOM::GeomObjPtr> EntityGUI_FeatureDetectorDlg::getSourceObjects()
961 {
962   QList<GEOM::GeomObjPtr> res;
963   res << myFace;
964   return res;
965 }