Salome HOME
a13fef61732794e12d99c8acb863f311f90112b7
[modules/geom.git] / src / EntityGUI / EntityGUI_FeatureDetectorDlg.cxx
1 // Copyright (C) 2007-2023  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; break;
622     case 1: aCornersParameters->typeCriteria = CV_TERMCRIT_EPS; break;
623     case 2: aCornersParameters->typeCriteria = CV_TERMCRIT_ITER | CV_TERMCRIT_EPS; break;
624     default: break;
625     }
626     aCornersParameters->maxIter = (dynamic_cast<QSpinBox*>(myWidgets[MAX_ITER]))->value();
627     aCornersParameters->epsilon = (dynamic_cast<QDoubleSpinBox*>(myWidgets[EPSILON]))->value();
628     aParameters = aCornersParameters;
629   }
630   else if ( myConstructorId == CONTOURS ) {
631     if ( !myUseROI->isChecked() ) { 
632       ShapeRec_CannyParameters* aCannyParameters = dynamic_cast<ShapeRec_CannyParameters*>( aParameters );
633       if ( !aCannyParameters ) aCannyParameters = new ShapeRec_CannyParameters();
634       aCannyParameters->lowThreshold = (dynamic_cast<QSpinBox*>(myWidgets[LOW_THRESHOLD]))->value();
635       aCannyParameters->ratio        = (dynamic_cast<QSpinBox*>(myWidgets[RATIO]))->value();
636       aCannyParameters->L2gradient   = (dynamic_cast<QCheckBox*>(myWidgets[L2GRADIENT]))->isChecked();
637       aParameters = aCannyParameters;
638     }
639     else {
640       ShapeRec_ColorFilterParameters* aColorFilterParameters = dynamic_cast<ShapeRec_ColorFilterParameters*>( aParameters );
641       if ( !aColorFilterParameters ) aColorFilterParameters = new ShapeRec_ColorFilterParameters();
642       int aSmoothSize = (dynamic_cast<QSpinBox*>(myWidgets[SMOOTH_SIZE]))->value();
643       aColorFilterParameters->smoothSize  = aSmoothSize % 2 == 0 ? aSmoothSize - 1 : aSmoothSize;
644       aColorFilterParameters->histSize[0] = (dynamic_cast<QSpinBox*>(myWidgets[HBINS]))->value();
645       aColorFilterParameters->histSize[1] = (dynamic_cast<QSpinBox*>(myWidgets[SBINS]))->value();
646       switch ( (dynamic_cast<QComboBox*>(myWidgets[HIST_TYPE]))->currentIndex() ) {
647       case 0: aColorFilterParameters->histType = CV_HIST_ARRAY;  break;
648       case 1: aColorFilterParameters->histType = CV_HIST_SPARSE; break;
649       }
650       aColorFilterParameters->threshold    = (dynamic_cast<QDoubleSpinBox*>(myWidgets[THRESHOLD_VALUE]))->value();
651       aColorFilterParameters->maxThreshold = (dynamic_cast<QDoubleSpinBox*>(myWidgets[MAX_THRESHOLD]))->value();
652       aParameters = aColorFilterParameters;
653     }
654   }
655  
656   aParameters->kernelSize = ( (dynamic_cast<QComboBox*>(myWidgets[KERNEL_SIZE]))->currentText() ).toInt();
657   switch ( (dynamic_cast<QComboBox*>(myWidgets[FIND_CONTOURS_METHOD]))->currentIndex() ) {
658   case 0: aParameters->findContoursMethod = CV_CHAIN_APPROX_NONE;      break;
659   case 1: aParameters->findContoursMethod = CV_CHAIN_APPROX_SIMPLE;    break;
660   case 2: aParameters->findContoursMethod = CV_CHAIN_APPROX_TC89_L1;   break;
661   case 3: aParameters->findContoursMethod = CV_CHAIN_APPROX_TC89_KCOS; break;
662   }
663
664   return aParameters;
665 }
666
667 //=================================================================================
668 // function : setStartPnt( const QPoint& )
669 // purpose  :
670 //=================================================================================
671 void EntityGUI_FeatureDetectorDlg::setStartPnt(const gp_Pnt& theStartPnt)
672 {
673   myStartPnt = theStartPnt;
674   MESSAGE("myStartPnt = ("<<theStartPnt.X()<<", "<<theStartPnt.Y()<<")");
675 }
676
677 //=================================================================================
678 // function : setEndPnt( const QPoint& )
679 // purpose  :
680 //=================================================================================
681 void EntityGUI_FeatureDetectorDlg::setEndPnt(const gp_Pnt& theEndPnt)
682 {
683   myEndPnt = theEndPnt;
684   MESSAGE("myEndPnt = ("<<theEndPnt.X()<<", "<<theEndPnt.Y()<<")");
685   if (setSelectionRect() && myDetector->GetImgHeight() > 0)
686     showImageSample();
687 }
688
689 //=================================================================================
690 // function : setSelectionRect()
691 // purpose  :
692 //=================================================================================
693 bool EntityGUI_FeatureDetectorDlg::setSelectionRect()
694
695   // Set detection rectangle in the background image coordinates system
696   double left    = std::min( myStartPnt.X(), myEndPnt.X() );
697   double top     = std::max( myStartPnt.Y(), myEndPnt.Y() );
698   double right   = std::max( myStartPnt.X(), myEndPnt.X() );
699   double bottom  = std::min( myStartPnt.Y(), myEndPnt.Y() );
700   
701   QPoint topLeft     = QPoint(left  - pictureLeft, pictureTop - top   );
702   QPoint bottomRight = QPoint(right - pictureLeft, pictureTop - bottom);
703   
704   myRect = QRect(topLeft, bottomRight);
705   
706   return (!myRect.isEmpty() && myRect.width() > 1);
707 }
708
709 //=================================================================================
710 // function : showImageSample()
711 // purpose  : Display a preview of the image sample selected by the user
712 //=================================================================================
713 void EntityGUI_FeatureDetectorDlg::showImageSample()
714
715   // Cropp the image to the selection rectangle given by the user
716   myDetector->SetROI( myRect ); 
717   std::string samplePicturePath = myDetector->CroppImage();
718   
719   // Display the result
720   QPixmap pixmap(QString(samplePicturePath.c_str()));
721   mySelectionGroup->FrameLabel->setPixmap(pixmap);
722   mySelectionGroup->FrameLabel->setMask(pixmap.mask());
723 }
724
725 //=================================================================================
726 // function : createOperation
727 // purpose  :
728 //=================================================================================
729 GEOM::GEOM_IOperations_ptr EntityGUI_FeatureDetectorDlg::createOperation()
730 {
731   return myGeomGUI->GetGeomGen()->GetIShapesOperations();
732 }
733
734 //=================================================================================
735 // function : execute()
736 // purpose  :
737 //=================================================================================
738 bool EntityGUI_FeatureDetectorDlg::execute( ObjectList& objects )
739 {
740   bool res = false;
741   
742   GEOM::GEOM_IBasicOperations_var  aBasicOperations  = myGeomGUI->GetGeomGen()->GetIBasicOperations();
743   GEOM::GEOM_IShapesOperations_var aShapesOperations = GEOM::GEOM_IShapesOperations::_narrow( getOperation() );
744
745   ShapeRec_Parameters* parameters = parametersChanged();
746   if ( !parameters ) parameters = new ShapeRec_Parameters();
747
748   bool useROI = myUseROI->isChecked() && !myRect.isEmpty();
749   try {
750     if (myConstructorId == CORNERS)
751     {
752       double subPictureLeft;
753       double subPictureTop;
754       if( useROI )
755       {
756         subPictureLeft    = myStartPnt.X();                
757         subPictureTop     = myStartPnt.Y();
758       }
759       else
760       {
761         subPictureLeft    = pictureLeft;
762         subPictureTop     = pictureTop;
763       }
764       myDetector->ComputeCorners( useROI, parameters );
765       CvPoint2D32f* corners     = myDetector->GetCorners();
766       int cornerCount           = myDetector->GetCornerCount();
767       int i;
768     
769       // Build the geom objects associated to the detected corners and returned by execute   
770       if( !aBasicOperations->_is_nil() && !aShapesOperations->_is_nil() ) 
771       {
772         GEOM::GEOM_Object_var  aGeomCorner;
773         GEOM::ListOfGO_var     geomCorners = new GEOM::ListOfGO();
774         geomCorners->length( cornerCount );
775         for (i = 0; i < cornerCount; i++)
776         {
777           double x = subPictureLeft + corners[i].x;
778           double y = subPictureTop  - corners[i].y;
779           double z =  0;
780         
781           aGeomCorner = aBasicOperations->MakePointXYZ( x,y,z );
782         
783           geomCorners[i] = aGeomCorner;  
784         } 
785         GEOM::GEOM_Object_var aCompound = aShapesOperations->MakeCompound(geomCorners);    
786         if ( !aCompound->_is_nil() )
787         {
788           // Dark blue color
789           SALOMEDS::Color aColor;
790           aColor.R = 0;
791           aColor.G = 0;
792           aColor.B = 0.8;
793
794           aCompound->SetColor(aColor);
795           aCompound->SetMarkerStd(GEOM::MT_POINT,GEOM::MS_30);
796           objects.push_back( aCompound._retn() );
797           res = true;
798         }
799       }   
800     }
801     else if (myConstructorId == CONTOURS)
802     {    
803       GEOM::GEOM_ICurvesOperations_var aCurveOperations = myGeomGUI->GetGeomGen()->GetICurvesOperations();
804
805       myDetector->ComputeContours( useROI, parameters );
806       std::vector< std::vector<cv::Point> >   contours  = myDetector->GetContours();
807       std::vector<cv::Vec4i>                  hierarchy = myDetector->GetContoursHierarchy();
808     
809       std::vector< cv::Point >                contour;
810       int idx = 0;
811       
812       GEOM::ListOfGO_var                      geomContours = new GEOM::ListOfGO();
813       int contourCount = 0;
814     
815       bool insert;
816     
817       MESSAGE("hierarchy.size() =" << hierarchy.size());
818       if ( hierarchy.size() < 1 ) {
819         getOperation()->SetErrorCode( "Impossible detected contours" );
820         return false;
821       }
822
823       for( ; idx >= 0; idx = hierarchy[idx][0])
824       {
825 //       for(int count=0, child=idx; child>=0, count<1; child=hierarchy[idx][2], count++)
826 //       {     
827 //         contour = contours[child];
828         contour = contours[idx];
829         std::vector< cv::Point >::iterator it;
830         std::vector< cv::Point >::iterator it_previous;
831         std::vector< cv::Point >::iterator it_next;
832         GEOM::GEOM_Object_var  aGeomContourPnt;
833         GEOM::ListOfGO_var     geomContourPnts = new GEOM::ListOfGO();
834        
835         geomContourPnts->length( contour.size() );
836
837         int j = 0;
838         std::set< std::vector<int> > existing_points;
839         std::pair< std::set< std::vector<int> >::iterator,bool > pnt_it;
840         for ( it=contour.begin() ; it < contour.end()-1; it++ )
841         {
842           int pnt_array[] = {it->x,it->y};     
843           std::vector<int> pnt (pnt_array, pnt_array + sizeof(pnt_array) / sizeof(int) );
844
845           pnt_it=existing_points.insert(pnt);
846           if (pnt_it.second == true)         // To avoid double points in the contours
847           {
848             insert = true;
849             if (it!=contour.begin())         // From the second point on perform some checking to avoid loops in the contours we build
850             {
851               it_previous = boost::prior(it);
852               it_next = boost::next(it);
853               
854               double u_v_scalar_product = (it->x - it_previous->x) * (it_next->x - it->x) + 
855                                           (it->y - it_previous->y) * (it_next->y - it->y);                                       
856               if (u_v_scalar_product < 0)
857               {
858                 double u_v_det = (it->x - it_previous->x) * (it_next->y - it->y) - 
859                                  (it->y - it_previous->y) * (it_next->x - it->x);
860                                           
861                 double norme_u = sqrt ( double(it->x - it_previous->x) * double(it->x - it_previous->x) +
862                                         double(it->y - it_previous->y) * double(it->y - it_previous->y) );
863                 
864                 double norme_v = sqrt ( double(it->x - it_next->x) * double(it->x - it_next->x) +
865                                         double(it->y - it_next->y) * double(it->y - it_next->y) );
866                                                                                                 
867                 double u_v_sinus = u_v_det / (norme_u * norme_v);
868                 
869                 if (fabs(u_v_sinus) < Precision::Confusion())
870                 { 
871                   insert = false;
872                 }                         
873               }
874             }
875             double x = -0.5 *width  + it->x;
876             double y =  0.5 *height - it->y;
877             double z =  0;
878             if (insert)
879             {
880               aGeomContourPnt    = aBasicOperations->MakePointXYZ( x,y,z );
881               geomContourPnts->length( j+1 );
882               geomContourPnts[j] = aGeomContourPnt;
883               j++;
884             }
885           }
886         }
887         
888         GEOM::GEOM_Object_var aWire;
889         if(myOutputGroup->RadioButton2->isChecked())
890         {
891           aWire = aCurveOperations->MakePolyline(geomContourPnts.in(), false);
892         }
893         else if(myOutputGroup->RadioButton1->isChecked())
894         {
895           aWire = aCurveOperations->MakeSplineInterpolation(geomContourPnts.in(), /*closed =*/ false, /*reordering =*/ false);
896         }
897         else
898           return res;
899         
900         if ( !aWire->_is_nil() )
901         {
902           geomContours->length(contourCount + 1);
903           geomContours[contourCount] = aWire;
904           contourCount++;
905         }
906 //       }
907       }
908       GEOM::GEOM_Object_var aContoursCompound = aShapesOperations->MakeCompound(geomContours);
909       if ( !aContoursCompound->_is_nil() )
910       {
911         objects.push_back( aContoursCompound._retn() );
912       }
913       res=true;
914     }
915   }
916   catch( ... ) {
917     getOperation()->SetErrorCode( "Impossible detected contours/corners" );
918     return false;
919   }
920   
921   // TEST not very conclusive
922   
923 //   else if(myConstructorId ==LINES)
924 //   {
925 //     myDetector->ComputeLines();
926 //     std::vector<cv::Vec4i>  lines = myDetector->GetLines();
927 //     GEOM::GEOM_Object_var  Pnt1;
928 //     GEOM::GEOM_Object_var  Pnt2;
929 //     GEOM::GEOM_Object_var  aLine;
930 //     
931 //     GEOM::ListOfGO_var     geomLines = new GEOM::ListOfGO();
932 //     int linesCount=0;
933 //     for( int i = 0; i < lines.size(); i++ )
934 //     {
935 //       Pnt1 = aBasicOperations->MakePointXYZ( -0.5 *width + lines[i][0], 0.5 *height - lines[i][1], 0 );
936 //       Pnt2 = aBasicOperations->MakePointXYZ( -0.5 *width + lines[i][2], 0.5 *height - lines[i][3], 0 );
937 //       aLine = aBasicOperations->MakeLineTwoPnt( Pnt1, Pnt2 );
938 //       if ( !aLine->_is_nil() )
939 //       {
940 //         geomLines->length(linesCount + 1);
941 //         geomLines[linesCount] = aLine;
942 //         linesCount++;
943 //       }
944 //     }
945 //     GEOM::GEOM_Object_var aLinesCompound = aShapesOperations->MakeCompound(geomLines);
946 //     if ( !aLinesCompound->_is_nil() )
947 //     {
948 //       objects.push_back( aLinesCompound._retn() );
949 //     }
950 // 
951 //     res=true;
952 //   }
953   
954   return res;
955 }
956
957 //=================================================================================
958 // function : getSourceObjects
959 // purpose  : virtual method to get source objects
960 //=================================================================================
961 QList<GEOM::GeomObjPtr> EntityGUI_FeatureDetectorDlg::getSourceObjects()
962 {
963   QList<GEOM::GeomObjPtr> res;
964   res << myFace;
965   return res;
966 }