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