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