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