]> SALOME platform Git repositories - modules/geom.git/blob - src/ShapeRecognition/ShapeRec_FeatureDetector.cxx
Salome HOME
rnc: some code refactoring
[modules/geom.git] / src / ShapeRecognition / ShapeRec_FeatureDetector.cxx
1 // Copyright (C) 2007-2011  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 // File   : ShapeRec_FeatureDetector.cxx
23 // Author : Renaud NEDELEC, Open CASCADE S.A.S.
24
25 #include "ShapeRec_FeatureDetector.hxx"
26 #include <stdio.h>
27 #include "utilities.h"
28
29 using namespace cv;
30
31 //TODO : All the following methods but ComputeContours use the C API of OpenCV while ComputContours
32 // uses the C++ API of the library.
33 // This should be homogenized and preferably by using the C++ API (which is more recent for all the methods
34
35 // The code has to be "cleaned up" too
36
37 /*!
38   Constructor
39   \param theFilename - image to process
40 */
41 ShapeRec_FeatureDetector::ShapeRec_FeatureDetector(const std::string& theFilename): 
42   corners()
43 {
44   cornerCount = 2000;
45   rect=cvRect(0,0,0,0);
46   imagePath = theFilename;
47   // Store the dimensions of the picture
48   IplImage* bg_img = cvLoadImage (imagePath.c_str(), CV_LOAD_IMAGE_GRAYSCALE);
49   imgHeight = bg_img->height;
50   imgWidth  = bg_img->width; 
51 }
52
53 /*!
54   Computes the corners of the image located at imagePath
55 */
56 void ShapeRec_FeatureDetector::ComputeCorners(){
57   
58   // Parameters for the corner detection
59   double qualityLevel = 0.2;
60   double minDistance = 1;
61  
62   // Images to be used for detection
63   IplImage *eig_img, *temp_img, *src_img_gray;
64   
65   // Load image
66   src_img_gray = cvLoadImage (imagePath.c_str(), CV_LOAD_IMAGE_GRAYSCALE);
67   
68   if ( rect.width > 1 )
69   {
70     // If a ROI as been set use it for detection
71     cvSetImageROI( src_img_gray, rect );
72   }
73   
74   eig_img = cvCreateImage (cvGetSize (src_img_gray), IPL_DEPTH_32F, 1);
75   temp_img = cvCreateImage (cvGetSize (src_img_gray), IPL_DEPTH_32F, 1);
76   corners = (CvPoint2D32f *) cvAlloc (cornerCount * sizeof (CvPoint2D32f));
77   
78   // image height and width
79   imgHeight = src_img_gray->height;
80   imgWidth  = src_img_gray->width;
81
82   // Corner detection using cvCornerMinEigenVal 
83   // (one of the methods available inOpenCV, there is also a cvConerHarris method that can be used by setting a flag in cvGoodFeaturesToTrack)
84   cvGoodFeaturesToTrack (src_img_gray, eig_img, temp_img, corners, &cornerCount, /*quality-level=*/qualityLevel, /*min-distance=*/minDistance);
85   cvFindCornerSubPix (src_img_gray, corners, cornerCount,
86                     cvSize (3, 3), cvSize (-1, -1), cvTermCriteria (CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03));
87
88   cvReleaseImage (&eig_img);
89   cvReleaseImage (&temp_img);
90   cvReleaseImage (&src_img_gray);
91
92 }
93
94 /*!
95   Computes the contours of the image located at imagePath
96 */
97 bool ShapeRec_FeatureDetector::ComputeContours( int detection_method ){
98  
99   // Initialising images
100   Mat src, src_gray;
101   Mat detected_edges;
102   
103   // Read image
104   src = imread( imagePath.c_str() );
105   if( !src.data )
106     return false; 
107   
108   if ( detection_method == CANNY )   // The problem is that with that filter the detector detects double contours
109   {   
110     // Thresholds for Canny detector
111     int lowThreshold = 100;
112     int ratio = 3;
113     int kernel_size = 3; // 3,5 or 7
114     
115     // Convert the image to grayscale
116     if (src.channels() == 3)
117       cvtColor( src, src_gray, CV_BGR2GRAY );
118     else if (src.channels() == 1)
119       src_gray = src;
120   
121     // Reduce noise with a kernel 3x3               
122     blur( src_gray, detected_edges, Size(3,3) );
123     // Canny detector
124     Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size, /*L2gradient =*/true );      
125   }
126   else if ( detection_method == COLORFILTER )
127   {
128     if ( !rect.width > 1 )
129       return false;
130     detected_edges = _colorFiltering();
131   }
132   else if ( detection_method == RIDGE_DETECTOR )  // Method adapted for engineering drawings (e.g. watershed functionnality could be used here cf.OpenCV documentation and samples)
133   {
134     // TODO
135     return false;
136   }
137   _detectAndRetrieveContours( detected_edges );
138   
139   return true;
140   
141 }
142
143 /*!
144   Computes the lines in the image located at imagePath
145 */
146 bool ShapeRec_FeatureDetector::ComputeLines(){
147   MESSAGE("ShapeRec_FeatureDetector::ComputeLines()")
148   // Initialising images
149   Mat src, src_gray, detected_edges, dst;
150   
151   src=imread(imagePath.c_str(), 0);
152   
153   Canny( src, dst, 50, 200, 3 );
154   HoughLinesP( dst, lines, 1, CV_PI/180, 80, 30, 10 );
155   return true;
156   
157 }
158
159 /*!
160   Stores a region of interest given by user in rect
161   \param theRect - Region Of Interest of the image located at imagePath 
162 */
163 void ShapeRec_FeatureDetector::SetROI( const QRect& theRect )
164 {
165   if (!theRect.isEmpty()){
166     rect = cvRect(theRect.x(),theRect.y(),theRect.width(),theRect.height());
167   }
168 }
169
170 /*!
171   Performs contours detection and store them in contours 
172   \param src - src image to find contours of 
173 */
174 void ShapeRec_FeatureDetector::_detectAndRetrieveContours( Mat src )
175 {
176   src = src > 1; 
177   int method = CV_CHAIN_APPROX_NONE;
178   findContours( src, contours, hierarchy,CV_RETR_CCOMP, method);
179   // Other possible approximations CV_CHAIN_APPROX_TC89_KCOS, CV_CHAIN_APPROX_TC89_L1, CV_CHAIN_APPROX_SIMPLE cf. OpenCV documentation 
180   // for precise information
181 }
182
183 /*!
184   Performs color filtering from the image sample contained in the ROI rect of the image 
185   located at imagePath
186   Thresholds the result in order ot obtain a binary image
187   \return binary image resulting from filtering and thersholding
188 */
189 Mat ShapeRec_FeatureDetector::_colorFiltering()
190 {  
191   IplImage* find_image = cvLoadImage(imagePath.c_str(),CV_LOAD_IMAGE_COLOR);
192   // Reduce noise with a kernel 3x3               
193   cvSmooth( find_image, find_image, CV_GAUSSIAN, 3, 3 );
194   
195   if ( !rect.width > 1 )
196     return Mat(find_image);
197   
198   // Crop the image to build an histogram from the selected part
199   cvSetImageROI(find_image, rect);
200   IplImage* test_image = cvCreateImage(cvGetSize(find_image),
201                                       find_image->depth,
202                                       find_image->nChannels);
203   cvCopy(find_image, test_image, NULL);
204   cvResetImageROI(find_image);
205   
206   IplImage* test_hsv = cvCreateImage(cvGetSize(test_image),8,3);
207   IplImage* test_hue = cvCreateImage(cvGetSize(test_image),8,1);
208   CvHistogram* hist;
209
210   cvCvtColor(test_image, test_hsv, CV_BGR2HSV);
211   cvCvtPixToPlane(test_hsv, test_hue, 0, 0, 0);
212   
213   //create hist
214   int size_hist = 10;
215   float hranges[] = {0, 180};
216   float* ranges = hranges;
217   hist = cvCreateHist(1, &size_hist, CV_HIST_ARRAY, &ranges, 1);
218   
219   //calculate hue` histogram
220   cvCalcHist(&test_hue, hist, 0 ,0);
221
222 //   // TEST print of the histogram for debugging
223 //   IplImage* hist_image = cvCreateImage(cvSize(320,300),8,3);
224 //   
225 //   //draw hist on hist_test image.
226 //   cvZero(hist_image);
227 //   float max_value = 0;
228 //   cvGetMinMaxHistValue(hist, 0 , &max_value, 0, 0);
229 //   int bin_w = hist_image->width/size_hist;
230 //   for(int i = 0; i < size_hist; i++ )
231 //   {
232 //     //prevent overflow
233 //     int val = cvRound( cvGetReal1D(hist->bins,i)*hist_image->
234 //     height/max_value);
235 //     CvScalar color = CV_RGB(200,0,0);
236 //     //hsv2rgb(i*180.f/size_hist);
237 //     cvRectangle( hist_image, cvPoint(i*bin_w,hist_image->height),
238 //     cvPoint((i+1)*bin_w,hist_image->height - val),
239 //     color, -1, 8, 0 );
240 //   }
241 //  
242 //    
243 //   cvNamedWindow("hist", 1); cvShowImage("hist",hist_image);
244   
245   
246   //calculate back projection of hue plane of input image
247   IplImage* backproject = cvCreateImage(cvGetSize(find_image), 8, 1);
248   IplImage* binary_backproject = cvCreateImage(cvGetSize(find_image), 8, 1);
249   IplImage* find_hsv = cvCreateImage(cvGetSize(find_image),8,3);
250   IplImage* find_hue = cvCreateImage(cvGetSize(find_image),8,1);
251   
252   cvCvtColor(find_image, find_hsv, CV_BGR2HSV);
253   cvCvtPixToPlane(find_hsv, find_hue, 0, 0, 0);
254   cvCalcBackProject(&find_hue, backproject, hist);
255   
256   // Threshold in order to obtain binary image
257   cvThreshold(backproject, binary_backproject, 1, 255, CV_THRESH_BINARY);  // NOTE it would be good to think about the best threshold to use (it's 1 for now)
258   cvReleaseImage(&test_image);
259   cvReleaseImage(&test_hsv);
260   cvReleaseImage(&test_hue);
261   cvReleaseImage(&backproject);
262   
263   return Mat(binary_backproject);
264 }