1 // Copyright (C) 2007-2011 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : ShapeRec_FeatureDetector.cxx
23 // Author : Renaud NEDELEC, Open CASCADE S.A.S.
25 #include "ShapeRec_FeatureDetector.hxx"
27 #include "utilities.h"
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
35 // The code has to be "cleaned up" too
39 \param theFilename - image to process
41 ShapeRec_FeatureDetector::ShapeRec_FeatureDetector(const std::string& theFilename):
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;
54 Computes the corners of the image located at imagePath
56 void ShapeRec_FeatureDetector::ComputeCorners(){
58 // Parameters for the corner detection
59 double qualityLevel = 0.2;
60 double minDistance = 1;
62 // Images to be used for detection
63 IplImage *eig_img, *temp_img, *src_img_gray;
66 src_img_gray = cvLoadImage (imagePath.c_str(), CV_LOAD_IMAGE_GRAYSCALE);
70 // If a ROI as been set use it for detection
71 cvSetImageROI( src_img_gray, rect );
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));
78 // image height and width
79 imgHeight = src_img_gray->height;
80 imgWidth = src_img_gray->width;
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));
88 cvReleaseImage (&eig_img);
89 cvReleaseImage (&temp_img);
90 cvReleaseImage (&src_img_gray);
95 Computes the contours of the image located at imagePath
97 bool ShapeRec_FeatureDetector::ComputeContours( int detection_method ){
99 // Initialising images
104 src = imread( imagePath.c_str() );
108 if ( detection_method == CANNY ) // The problem is that with that filter the detector detects double contours
110 // Thresholds for Canny detector
111 int lowThreshold = 100;
113 int kernel_size = 3; // 3,5 or 7
115 // Convert the image to grayscale
116 if (src.channels() == 3)
117 cvtColor( src, src_gray, CV_BGR2GRAY );
118 else if (src.channels() == 1)
121 // Reduce noise with a kernel 3x3
122 blur( src_gray, detected_edges, Size(3,3) );
124 Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size, /*L2gradient =*/true );
126 else if ( detection_method == COLORFILTER )
128 if ( !rect.width > 1 )
130 detected_edges = _colorFiltering();
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)
137 _detectAndRetrieveContours( detected_edges );
144 Computes the lines in the image located at imagePath
146 bool ShapeRec_FeatureDetector::ComputeLines(){
147 MESSAGE("ShapeRec_FeatureDetector::ComputeLines()")
148 // Initialising images
149 Mat src, src_gray, detected_edges, dst;
151 src=imread(imagePath.c_str(), 0);
153 Canny( src, dst, 50, 200, 3 );
154 HoughLinesP( dst, lines, 1, CV_PI/180, 80, 30, 10 );
160 Stores a region of interest given by user in rect
161 \param theRect - Region Of Interest of the image located at imagePath
163 void ShapeRec_FeatureDetector::SetROI( const QRect& theRect )
165 if (!theRect.isEmpty()){
166 rect = cvRect(theRect.x(),theRect.y(),theRect.width(),theRect.height());
171 Performs contours detection and store them in contours
172 \param src - src image to find contours of
174 void ShapeRec_FeatureDetector::_detectAndRetrieveContours( Mat src )
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
184 Performs color filtering from the image sample contained in the ROI rect of the image
186 Thresholds the result in order ot obtain a binary image
187 \return binary image resulting from filtering and thersholding
189 Mat ShapeRec_FeatureDetector::_colorFiltering()
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 );
195 if ( !rect.width > 1 )
196 return Mat(find_image);
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),
202 find_image->nChannels);
203 cvCopy(find_image, test_image, NULL);
204 cvResetImageROI(find_image);
206 IplImage* test_hsv = cvCreateImage(cvGetSize(test_image),8,3);
207 IplImage* test_hue = cvCreateImage(cvGetSize(test_image),8,1);
210 cvCvtColor(test_image, test_hsv, CV_BGR2HSV);
211 cvCvtPixToPlane(test_hsv, test_hue, 0, 0, 0);
215 float hranges[] = {0, 180};
216 float* ranges = hranges;
217 hist = cvCreateHist(1, &size_hist, CV_HIST_ARRAY, &ranges, 1);
219 //calculate hue` histogram
220 cvCalcHist(&test_hue, hist, 0 ,0);
222 // // TEST print of the histogram for debugging
223 // IplImage* hist_image = cvCreateImage(cvSize(320,300),8,3);
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++ )
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 );
243 // cvNamedWindow("hist", 1); cvShowImage("hist",hist_image);
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);
252 cvCvtColor(find_image, find_hsv, CV_BGR2HSV);
253 cvCvtPixToPlane(find_hsv, find_hue, 0, 0, 0);
254 cvCalcBackProject(&find_hue, backproject, hist);
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);
263 return Mat(binary_backproject);