Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/features2d/src/blobdetector.cpp
16337 views
1
/*M///////////////////////////////////////////////////////////////////////////////////////
2
//
3
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4
//
5
// By downloading, copying, installing or using the software you agree to this license.
6
// If you do not agree to this license, do not download, install,
7
// copy or use the software.
8
//
9
//
10
// License Agreement
11
// For Open Source Computer Vision Library
12
//
13
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15
// Third party copyrights are property of their respective owners.
16
//
17
// Redistribution and use in source and binary forms, with or without modification,
18
// are permitted provided that the following conditions are met:
19
//
20
// * Redistribution's of source code must retain the above copyright notice,
21
// this list of conditions and the following disclaimer.
22
//
23
// * Redistribution's in binary form must reproduce the above copyright notice,
24
// this list of conditions and the following disclaimer in the documentation
25
// and/or other materials provided with the distribution.
26
//
27
// * The name of the copyright holders may not be used to endorse or promote products
28
// derived from this software without specific prior written permission.
29
//
30
// This software is provided by the copyright holders and contributors "as is" and
31
// any express or implied warranties, including, but not limited to, the implied
32
// warranties of merchantability and fitness for a particular purpose are disclaimed.
33
// In no event shall the Intel Corporation or contributors be liable for any direct,
34
// indirect, incidental, special, exemplary, or consequential damages
35
// (including, but not limited to, procurement of substitute goods or services;
36
// loss of use, data, or profits; or business interruption) however caused
37
// and on any theory of liability, whether in contract, strict liability,
38
// or tort (including negligence or otherwise) arising in any way out of
39
// the use of this software, even if advised of the possibility of such damage.
40
//
41
//M*/
42
43
#include "precomp.hpp"
44
#include <iterator>
45
#include <limits>
46
47
//#define DEBUG_BLOB_DETECTOR
48
49
#ifdef DEBUG_BLOB_DETECTOR
50
# include "opencv2/opencv_modules.hpp"
51
# ifdef HAVE_OPENCV_HIGHGUI
52
# include "opencv2/highgui.hpp"
53
# else
54
# undef DEBUG_BLOB_DETECTOR
55
# endif
56
#endif
57
58
namespace cv
59
{
60
61
class CV_EXPORTS_W SimpleBlobDetectorImpl : public SimpleBlobDetector
62
{
63
public:
64
65
explicit SimpleBlobDetectorImpl(const SimpleBlobDetector::Params &parameters = SimpleBlobDetector::Params());
66
67
virtual void read( const FileNode& fn ) CV_OVERRIDE;
68
virtual void write( FileStorage& fs ) const CV_OVERRIDE;
69
70
protected:
71
struct CV_EXPORTS Center
72
{
73
Point2d location;
74
double radius;
75
double confidence;
76
};
77
78
virtual void detect( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) CV_OVERRIDE;
79
virtual void findBlobs(InputArray image, InputArray binaryImage, std::vector<Center> &centers) const;
80
81
Params params;
82
};
83
84
/*
85
* SimpleBlobDetector
86
*/
87
SimpleBlobDetector::Params::Params()
88
{
89
thresholdStep = 10;
90
minThreshold = 50;
91
maxThreshold = 220;
92
minRepeatability = 2;
93
minDistBetweenBlobs = 10;
94
95
filterByColor = true;
96
blobColor = 0;
97
98
filterByArea = true;
99
minArea = 25;
100
maxArea = 5000;
101
102
filterByCircularity = false;
103
minCircularity = 0.8f;
104
maxCircularity = std::numeric_limits<float>::max();
105
106
filterByInertia = true;
107
//minInertiaRatio = 0.6;
108
minInertiaRatio = 0.1f;
109
maxInertiaRatio = std::numeric_limits<float>::max();
110
111
filterByConvexity = true;
112
//minConvexity = 0.8;
113
minConvexity = 0.95f;
114
maxConvexity = std::numeric_limits<float>::max();
115
}
116
117
void SimpleBlobDetector::Params::read(const cv::FileNode& fn )
118
{
119
thresholdStep = fn["thresholdStep"];
120
minThreshold = fn["minThreshold"];
121
maxThreshold = fn["maxThreshold"];
122
123
minRepeatability = (size_t)(int)fn["minRepeatability"];
124
minDistBetweenBlobs = fn["minDistBetweenBlobs"];
125
126
filterByColor = (int)fn["filterByColor"] != 0 ? true : false;
127
blobColor = (uchar)(int)fn["blobColor"];
128
129
filterByArea = (int)fn["filterByArea"] != 0 ? true : false;
130
minArea = fn["minArea"];
131
maxArea = fn["maxArea"];
132
133
filterByCircularity = (int)fn["filterByCircularity"] != 0 ? true : false;
134
minCircularity = fn["minCircularity"];
135
maxCircularity = fn["maxCircularity"];
136
137
filterByInertia = (int)fn["filterByInertia"] != 0 ? true : false;
138
minInertiaRatio = fn["minInertiaRatio"];
139
maxInertiaRatio = fn["maxInertiaRatio"];
140
141
filterByConvexity = (int)fn["filterByConvexity"] != 0 ? true : false;
142
minConvexity = fn["minConvexity"];
143
maxConvexity = fn["maxConvexity"];
144
}
145
146
void SimpleBlobDetector::Params::write(cv::FileStorage& fs) const
147
{
148
fs << "thresholdStep" << thresholdStep;
149
fs << "minThreshold" << minThreshold;
150
fs << "maxThreshold" << maxThreshold;
151
152
fs << "minRepeatability" << (int)minRepeatability;
153
fs << "minDistBetweenBlobs" << minDistBetweenBlobs;
154
155
fs << "filterByColor" << (int)filterByColor;
156
fs << "blobColor" << (int)blobColor;
157
158
fs << "filterByArea" << (int)filterByArea;
159
fs << "minArea" << minArea;
160
fs << "maxArea" << maxArea;
161
162
fs << "filterByCircularity" << (int)filterByCircularity;
163
fs << "minCircularity" << minCircularity;
164
fs << "maxCircularity" << maxCircularity;
165
166
fs << "filterByInertia" << (int)filterByInertia;
167
fs << "minInertiaRatio" << minInertiaRatio;
168
fs << "maxInertiaRatio" << maxInertiaRatio;
169
170
fs << "filterByConvexity" << (int)filterByConvexity;
171
fs << "minConvexity" << minConvexity;
172
fs << "maxConvexity" << maxConvexity;
173
}
174
175
SimpleBlobDetectorImpl::SimpleBlobDetectorImpl(const SimpleBlobDetector::Params &parameters) :
176
params(parameters)
177
{
178
}
179
180
void SimpleBlobDetectorImpl::read( const cv::FileNode& fn )
181
{
182
params.read(fn);
183
}
184
185
void SimpleBlobDetectorImpl::write( cv::FileStorage& fs ) const
186
{
187
writeFormat(fs);
188
params.write(fs);
189
}
190
191
void SimpleBlobDetectorImpl::findBlobs(InputArray _image, InputArray _binaryImage, std::vector<Center> &centers) const
192
{
193
CV_INSTRUMENT_REGION();
194
195
Mat image = _image.getMat(), binaryImage = _binaryImage.getMat();
196
CV_UNUSED(image);
197
centers.clear();
198
199
std::vector < std::vector<Point> > contours;
200
Mat tmpBinaryImage = binaryImage.clone();
201
findContours(tmpBinaryImage, contours, RETR_LIST, CHAIN_APPROX_NONE);
202
203
#ifdef DEBUG_BLOB_DETECTOR
204
// Mat keypointsImage;
205
// cvtColor( binaryImage, keypointsImage, CV_GRAY2RGB );
206
//
207
// Mat contoursImage;
208
// cvtColor( binaryImage, contoursImage, CV_GRAY2RGB );
209
// drawContours( contoursImage, contours, -1, Scalar(0,255,0) );
210
// imshow("contours", contoursImage );
211
#endif
212
213
for (size_t contourIdx = 0; contourIdx < contours.size(); contourIdx++)
214
{
215
Center center;
216
center.confidence = 1;
217
Moments moms = moments(Mat(contours[contourIdx]));
218
if (params.filterByArea)
219
{
220
double area = moms.m00;
221
if (area < params.minArea || area >= params.maxArea)
222
continue;
223
}
224
225
if (params.filterByCircularity)
226
{
227
double area = moms.m00;
228
double perimeter = arcLength(Mat(contours[contourIdx]), true);
229
double ratio = 4 * CV_PI * area / (perimeter * perimeter);
230
if (ratio < params.minCircularity || ratio >= params.maxCircularity)
231
continue;
232
}
233
234
if (params.filterByInertia)
235
{
236
double denominator = std::sqrt(std::pow(2 * moms.mu11, 2) + std::pow(moms.mu20 - moms.mu02, 2));
237
const double eps = 1e-2;
238
double ratio;
239
if (denominator > eps)
240
{
241
double cosmin = (moms.mu20 - moms.mu02) / denominator;
242
double sinmin = 2 * moms.mu11 / denominator;
243
double cosmax = -cosmin;
244
double sinmax = -sinmin;
245
246
double imin = 0.5 * (moms.mu20 + moms.mu02) - 0.5 * (moms.mu20 - moms.mu02) * cosmin - moms.mu11 * sinmin;
247
double imax = 0.5 * (moms.mu20 + moms.mu02) - 0.5 * (moms.mu20 - moms.mu02) * cosmax - moms.mu11 * sinmax;
248
ratio = imin / imax;
249
}
250
else
251
{
252
ratio = 1;
253
}
254
255
if (ratio < params.minInertiaRatio || ratio >= params.maxInertiaRatio)
256
continue;
257
258
center.confidence = ratio * ratio;
259
}
260
261
if (params.filterByConvexity)
262
{
263
std::vector < Point > hull;
264
convexHull(Mat(contours[contourIdx]), hull);
265
double area = contourArea(Mat(contours[contourIdx]));
266
double hullArea = contourArea(Mat(hull));
267
if (fabs(hullArea) < DBL_EPSILON)
268
continue;
269
double ratio = area / hullArea;
270
if (ratio < params.minConvexity || ratio >= params.maxConvexity)
271
continue;
272
}
273
274
if(moms.m00 == 0.0)
275
continue;
276
center.location = Point2d(moms.m10 / moms.m00, moms.m01 / moms.m00);
277
278
if (params.filterByColor)
279
{
280
if (binaryImage.at<uchar> (cvRound(center.location.y), cvRound(center.location.x)) != params.blobColor)
281
continue;
282
}
283
284
//compute blob radius
285
{
286
std::vector<double> dists;
287
for (size_t pointIdx = 0; pointIdx < contours[contourIdx].size(); pointIdx++)
288
{
289
Point2d pt = contours[contourIdx][pointIdx];
290
dists.push_back(norm(center.location - pt));
291
}
292
std::sort(dists.begin(), dists.end());
293
center.radius = (dists[(dists.size() - 1) / 2] + dists[dists.size() / 2]) / 2.;
294
}
295
296
centers.push_back(center);
297
298
299
#ifdef DEBUG_BLOB_DETECTOR
300
// circle( keypointsImage, center.location, 1, Scalar(0,0,255), 1 );
301
#endif
302
}
303
#ifdef DEBUG_BLOB_DETECTOR
304
// imshow("bk", keypointsImage );
305
// waitKey();
306
#endif
307
}
308
309
void SimpleBlobDetectorImpl::detect(InputArray image, std::vector<cv::KeyPoint>& keypoints, InputArray mask)
310
{
311
CV_INSTRUMENT_REGION();
312
313
keypoints.clear();
314
CV_Assert(params.minRepeatability != 0);
315
Mat grayscaleImage;
316
if (image.channels() == 3 || image.channels() == 4)
317
cvtColor(image, grayscaleImage, COLOR_BGR2GRAY);
318
else
319
grayscaleImage = image.getMat();
320
321
if (grayscaleImage.type() != CV_8UC1) {
322
CV_Error(Error::StsUnsupportedFormat, "Blob detector only supports 8-bit images!");
323
}
324
325
std::vector < std::vector<Center> > centers;
326
for (double thresh = params.minThreshold; thresh < params.maxThreshold; thresh += params.thresholdStep)
327
{
328
Mat binarizedImage;
329
threshold(grayscaleImage, binarizedImage, thresh, 255, THRESH_BINARY);
330
331
std::vector < Center > curCenters;
332
findBlobs(grayscaleImage, binarizedImage, curCenters);
333
std::vector < std::vector<Center> > newCenters;
334
for (size_t i = 0; i < curCenters.size(); i++)
335
{
336
bool isNew = true;
337
for (size_t j = 0; j < centers.size(); j++)
338
{
339
double dist = norm(centers[j][ centers[j].size() / 2 ].location - curCenters[i].location);
340
isNew = dist >= params.minDistBetweenBlobs && dist >= centers[j][ centers[j].size() / 2 ].radius && dist >= curCenters[i].radius;
341
if (!isNew)
342
{
343
centers[j].push_back(curCenters[i]);
344
345
size_t k = centers[j].size() - 1;
346
while( k > 0 && centers[j][k].radius < centers[j][k-1].radius )
347
{
348
centers[j][k] = centers[j][k-1];
349
k--;
350
}
351
centers[j][k] = curCenters[i];
352
353
break;
354
}
355
}
356
if (isNew)
357
newCenters.push_back(std::vector<Center> (1, curCenters[i]));
358
}
359
std::copy(newCenters.begin(), newCenters.end(), std::back_inserter(centers));
360
}
361
362
for (size_t i = 0; i < centers.size(); i++)
363
{
364
if (centers[i].size() < params.minRepeatability)
365
continue;
366
Point2d sumPoint(0, 0);
367
double normalizer = 0;
368
for (size_t j = 0; j < centers[i].size(); j++)
369
{
370
sumPoint += centers[i][j].confidence * centers[i][j].location;
371
normalizer += centers[i][j].confidence;
372
}
373
sumPoint *= (1. / normalizer);
374
KeyPoint kpt(sumPoint, (float)(centers[i][centers[i].size() / 2].radius) * 2.0f);
375
keypoints.push_back(kpt);
376
}
377
378
if (!mask.empty())
379
{
380
KeyPointsFilter::runByPixelsMask(keypoints, mask.getMat());
381
}
382
}
383
384
Ptr<SimpleBlobDetector> SimpleBlobDetector::create(const SimpleBlobDetector::Params& params)
385
{
386
return makePtr<SimpleBlobDetectorImpl>(params);
387
}
388
389
String SimpleBlobDetector::getDefaultName() const
390
{
391
return (Feature2D::getDefaultName() + ".SimpleBlobDetector");
392
}
393
394
}
395
396