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