blobdetector.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. #include "precomp.hpp"
  43. #include <iterator>
  44. #include <limits>
  45. #include <opencv2/core/utils/logger.hpp>
  46. // Requires CMake flag: DEBUG_opencv_features2d=ON
  47. //#define DEBUG_BLOB_DETECTOR
  48. #ifdef DEBUG_BLOB_DETECTOR
  49. #include "opencv2/highgui.hpp"
  50. #endif
  51. namespace cv
  52. {
  53. // TODO: To be removed in 5.x branch
  54. const std::vector<std::vector<cv::Point> >& SimpleBlobDetector::getBlobContours() const
  55. {
  56. CV_Error(Error::StsNotImplemented, "Method SimpleBlobDetector::getBlobContours() is not implemented");
  57. }
  58. class CV_EXPORTS_W SimpleBlobDetectorImpl : public SimpleBlobDetector
  59. {
  60. public:
  61. explicit SimpleBlobDetectorImpl(const SimpleBlobDetector::Params &parameters = SimpleBlobDetector::Params());
  62. virtual void read( const FileNode& fn ) CV_OVERRIDE;
  63. virtual void write( FileStorage& fs ) const CV_OVERRIDE;
  64. void setParams(const SimpleBlobDetector::Params& _params ) CV_OVERRIDE {
  65. SimpleBlobDetectorImpl::validateParameters(_params);
  66. params = _params;
  67. }
  68. SimpleBlobDetector::Params getParams() const CV_OVERRIDE { return params; }
  69. static void validateParameters(const SimpleBlobDetector::Params& p)
  70. {
  71. if (p.thresholdStep <= 0)
  72. CV_Error(Error::StsBadArg, "thresholdStep>0");
  73. if (p.minThreshold > p.maxThreshold || p.minThreshold < 0)
  74. CV_Error(Error::StsBadArg, "0<=minThreshold<=maxThreshold");
  75. if (p.minDistBetweenBlobs <=0 )
  76. CV_Error(Error::StsBadArg, "minDistBetweenBlobs>0");
  77. if (p.minArea > p.maxArea || p.minArea <=0)
  78. CV_Error(Error::StsBadArg, "0<minArea<=maxArea");
  79. if (p.minCircularity > p.maxCircularity || p.minCircularity <= 0)
  80. CV_Error(Error::StsBadArg, "0<minCircularity<=maxCircularity");
  81. if (p.minInertiaRatio > p.maxInertiaRatio || p.minInertiaRatio <= 0)
  82. CV_Error(Error::StsBadArg, "0<minInertiaRatio<=maxInertiaRatio");
  83. if (p.minConvexity > p.maxConvexity || p.minConvexity <= 0)
  84. CV_Error(Error::StsBadArg, "0<minConvexity<=maxConvexity");
  85. }
  86. protected:
  87. struct CV_EXPORTS Center
  88. {
  89. Point2d location;
  90. double radius;
  91. double confidence;
  92. };
  93. virtual void detect( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) CV_OVERRIDE;
  94. virtual void findBlobs(InputArray image, InputArray binaryImage, std::vector<Center> &centers,
  95. std::vector<std::vector<Point> > &contours, std::vector<Moments> &moments) const;
  96. virtual const std::vector<std::vector<Point> >& getBlobContours() const CV_OVERRIDE;
  97. Params params;
  98. std::vector<std::vector<Point> > blobContours;
  99. };
  100. /*
  101. * SimpleBlobDetector
  102. */
  103. SimpleBlobDetector::Params::Params()
  104. {
  105. thresholdStep = 10;
  106. minThreshold = 50;
  107. maxThreshold = 220;
  108. minRepeatability = 2;
  109. minDistBetweenBlobs = 10;
  110. filterByColor = true;
  111. blobColor = 0;
  112. filterByArea = true;
  113. minArea = 25;
  114. maxArea = 5000;
  115. filterByCircularity = false;
  116. minCircularity = 0.8f;
  117. maxCircularity = std::numeric_limits<float>::max();
  118. filterByInertia = true;
  119. //minInertiaRatio = 0.6;
  120. minInertiaRatio = 0.1f;
  121. maxInertiaRatio = std::numeric_limits<float>::max();
  122. filterByConvexity = true;
  123. //minConvexity = 0.8;
  124. minConvexity = 0.95f;
  125. maxConvexity = std::numeric_limits<float>::max();
  126. collectContours = false;
  127. }
  128. void SimpleBlobDetector::Params::read(const cv::FileNode& fn )
  129. {
  130. thresholdStep = fn["thresholdStep"];
  131. minThreshold = fn["minThreshold"];
  132. maxThreshold = fn["maxThreshold"];
  133. minRepeatability = (size_t)(int)fn["minRepeatability"];
  134. minDistBetweenBlobs = fn["minDistBetweenBlobs"];
  135. filterByColor = (int)fn["filterByColor"] != 0 ? true : false;
  136. blobColor = (uchar)(int)fn["blobColor"];
  137. filterByArea = (int)fn["filterByArea"] != 0 ? true : false;
  138. minArea = fn["minArea"];
  139. maxArea = fn["maxArea"];
  140. filterByCircularity = (int)fn["filterByCircularity"] != 0 ? true : false;
  141. minCircularity = fn["minCircularity"];
  142. maxCircularity = fn["maxCircularity"];
  143. filterByInertia = (int)fn["filterByInertia"] != 0 ? true : false;
  144. minInertiaRatio = fn["minInertiaRatio"];
  145. maxInertiaRatio = fn["maxInertiaRatio"];
  146. filterByConvexity = (int)fn["filterByConvexity"] != 0 ? true : false;
  147. minConvexity = fn["minConvexity"];
  148. maxConvexity = fn["maxConvexity"];
  149. collectContours = (int)fn["collectContours"] != 0 ? true : false;
  150. }
  151. void SimpleBlobDetector::Params::write(cv::FileStorage& fs) const
  152. {
  153. fs << "thresholdStep" << thresholdStep;
  154. fs << "minThreshold" << minThreshold;
  155. fs << "maxThreshold" << maxThreshold;
  156. fs << "minRepeatability" << (int)minRepeatability;
  157. fs << "minDistBetweenBlobs" << minDistBetweenBlobs;
  158. fs << "filterByColor" << (int)filterByColor;
  159. fs << "blobColor" << (int)blobColor;
  160. fs << "filterByArea" << (int)filterByArea;
  161. fs << "minArea" << minArea;
  162. fs << "maxArea" << maxArea;
  163. fs << "filterByCircularity" << (int)filterByCircularity;
  164. fs << "minCircularity" << minCircularity;
  165. fs << "maxCircularity" << maxCircularity;
  166. fs << "filterByInertia" << (int)filterByInertia;
  167. fs << "minInertiaRatio" << minInertiaRatio;
  168. fs << "maxInertiaRatio" << maxInertiaRatio;
  169. fs << "filterByConvexity" << (int)filterByConvexity;
  170. fs << "minConvexity" << minConvexity;
  171. fs << "maxConvexity" << maxConvexity;
  172. fs << "collectContours" << (int)collectContours;
  173. }
  174. SimpleBlobDetectorImpl::SimpleBlobDetectorImpl(const SimpleBlobDetector::Params &parameters) :
  175. params(parameters)
  176. {
  177. }
  178. void SimpleBlobDetectorImpl::read( const cv::FileNode& fn )
  179. {
  180. SimpleBlobDetector::Params rp;
  181. rp.read(fn);
  182. SimpleBlobDetectorImpl::validateParameters(rp);
  183. params = rp;
  184. }
  185. void SimpleBlobDetectorImpl::write( cv::FileStorage& fs ) const
  186. {
  187. writeFormat(fs);
  188. params.write(fs);
  189. }
  190. void SimpleBlobDetectorImpl::findBlobs(InputArray _image, InputArray _binaryImage, std::vector<Center> &centers,
  191. std::vector<std::vector<Point> > &contoursOut, std::vector<Moments> &momentss) const
  192. {
  193. CV_INSTRUMENT_REGION();
  194. Mat image = _image.getMat(), binaryImage = _binaryImage.getMat();
  195. CV_UNUSED(image);
  196. centers.clear();
  197. contoursOut.clear();
  198. momentss.clear();
  199. std::vector < std::vector<Point> > contours;
  200. findContours(binaryImage, contours, RETR_LIST, CHAIN_APPROX_NONE);
  201. #ifdef DEBUG_BLOB_DETECTOR
  202. Mat keypointsImage;
  203. cvtColor(binaryImage, keypointsImage, COLOR_GRAY2RGB);
  204. Mat contoursImage;
  205. cvtColor(binaryImage, contoursImage, COLOR_GRAY2RGB);
  206. drawContours( contoursImage, contours, -1, Scalar(0,255,0) );
  207. imshow("contours", contoursImage );
  208. #endif
  209. for (size_t contourIdx = 0; contourIdx < contours.size(); contourIdx++)
  210. {
  211. Center center;
  212. center.confidence = 1;
  213. Moments moms = moments(contours[contourIdx]);
  214. if (params.filterByArea)
  215. {
  216. double area = moms.m00;
  217. if (area < params.minArea || area >= params.maxArea)
  218. continue;
  219. }
  220. if (params.filterByCircularity)
  221. {
  222. double area = moms.m00;
  223. double perimeter = arcLength(contours[contourIdx], true);
  224. double ratio = 4 * CV_PI * area / (perimeter * perimeter);
  225. if (ratio < params.minCircularity || ratio >= params.maxCircularity)
  226. continue;
  227. }
  228. if (params.filterByInertia)
  229. {
  230. double denominator = std::sqrt(std::pow(2 * moms.mu11, 2) + std::pow(moms.mu20 - moms.mu02, 2));
  231. const double eps = 1e-2;
  232. double ratio;
  233. if (denominator > eps)
  234. {
  235. double cosmin = (moms.mu20 - moms.mu02) / denominator;
  236. double sinmin = 2 * moms.mu11 / denominator;
  237. double cosmax = -cosmin;
  238. double sinmax = -sinmin;
  239. double imin = 0.5 * (moms.mu20 + moms.mu02) - 0.5 * (moms.mu20 - moms.mu02) * cosmin - moms.mu11 * sinmin;
  240. double imax = 0.5 * (moms.mu20 + moms.mu02) - 0.5 * (moms.mu20 - moms.mu02) * cosmax - moms.mu11 * sinmax;
  241. ratio = imin / imax;
  242. }
  243. else
  244. {
  245. ratio = 1;
  246. }
  247. if (ratio < params.minInertiaRatio || ratio >= params.maxInertiaRatio)
  248. continue;
  249. center.confidence = ratio * ratio;
  250. }
  251. if (params.filterByConvexity)
  252. {
  253. std::vector < Point > hull;
  254. convexHull(contours[contourIdx], hull);
  255. double area = moms.m00;
  256. double hullArea = contourArea(hull);
  257. if (fabs(hullArea) < DBL_EPSILON)
  258. continue;
  259. double ratio = area / hullArea;
  260. if (ratio < params.minConvexity || ratio >= params.maxConvexity)
  261. continue;
  262. }
  263. if(moms.m00 == 0.0)
  264. continue;
  265. center.location = Point2d(moms.m10 / moms.m00, moms.m01 / moms.m00);
  266. if (params.filterByColor)
  267. {
  268. if (binaryImage.at<uchar> (cvRound(center.location.y), cvRound(center.location.x)) != params.blobColor)
  269. continue;
  270. }
  271. //compute blob radius
  272. {
  273. std::vector<double> dists;
  274. for (size_t pointIdx = 0; pointIdx < contours[contourIdx].size(); pointIdx++)
  275. {
  276. Point2d pt = contours[contourIdx][pointIdx];
  277. dists.push_back(norm(center.location - pt));
  278. }
  279. std::sort(dists.begin(), dists.end());
  280. center.radius = (dists[(dists.size() - 1) / 2] + dists[dists.size() / 2]) / 2.;
  281. }
  282. centers.push_back(center);
  283. if (params.collectContours)
  284. {
  285. contoursOut.push_back(contours[contourIdx]);
  286. momentss.push_back(moms);
  287. }
  288. #ifdef DEBUG_BLOB_DETECTOR
  289. circle( keypointsImage, center.location, 1, Scalar(0,0,255), 1 );
  290. #endif
  291. }
  292. #ifdef DEBUG_BLOB_DETECTOR
  293. imshow("bk", keypointsImage );
  294. waitKey();
  295. #endif
  296. }
  297. void SimpleBlobDetectorImpl::detect(InputArray image, std::vector<cv::KeyPoint>& keypoints, InputArray mask)
  298. {
  299. CV_INSTRUMENT_REGION();
  300. keypoints.clear();
  301. blobContours.clear();
  302. CV_Assert(params.minRepeatability != 0);
  303. Mat grayscaleImage;
  304. if (image.channels() == 3 || image.channels() == 4)
  305. cvtColor(image, grayscaleImage, COLOR_BGR2GRAY);
  306. else
  307. grayscaleImage = image.getMat();
  308. if (grayscaleImage.type() != CV_8UC1) {
  309. CV_Error(Error::StsUnsupportedFormat, "Blob detector only supports 8-bit images!");
  310. }
  311. CV_CheckGT(params.thresholdStep, 0.0f, "");
  312. if (params.minThreshold + params.thresholdStep >= params.maxThreshold)
  313. {
  314. // https://github.com/opencv/opencv/issues/6667
  315. CV_LOG_ONCE_INFO(NULL, "SimpleBlobDetector: params.minDistBetweenBlobs is ignored for case with single threshold");
  316. #if 0 // OpenCV 5.0
  317. CV_CheckEQ(params.minRepeatability, 1u, "Incompatible parameters for case with single threshold");
  318. #else
  319. if (params.minRepeatability != 1)
  320. CV_LOG_WARNING(NULL, "SimpleBlobDetector: params.minRepeatability=" << params.minRepeatability << " is incompatible for case with single threshold. Empty result is expected.");
  321. #endif
  322. }
  323. std::vector < std::vector<Center> > centers;
  324. std::vector<Moments> momentss;
  325. for (double thresh = params.minThreshold; thresh < params.maxThreshold; thresh += params.thresholdStep)
  326. {
  327. Mat binarizedImage;
  328. threshold(grayscaleImage, binarizedImage, thresh, 255, THRESH_BINARY);
  329. std::vector < Center > curCenters;
  330. std::vector<std::vector<Point> > curContours;
  331. std::vector<Moments> curMomentss;
  332. findBlobs(grayscaleImage, binarizedImage, curCenters, curContours, curMomentss);
  333. std::vector < std::vector<Center> > newCenters;
  334. std::vector<std::vector<Point> > newContours;
  335. std::vector<Moments> newMomentss;
  336. for (size_t i = 0; i < curCenters.size(); i++)
  337. {
  338. bool isNew = true;
  339. for (size_t j = 0; j < centers.size(); j++)
  340. {
  341. double dist = norm(centers[j][ centers[j].size() / 2 ].location - curCenters[i].location);
  342. isNew = dist >= params.minDistBetweenBlobs && dist >= centers[j][ centers[j].size() / 2 ].radius && dist >= curCenters[i].radius;
  343. if (!isNew)
  344. {
  345. centers[j].push_back(curCenters[i]);
  346. size_t k = centers[j].size() - 1;
  347. while( k > 0 && curCenters[i].radius < centers[j][k-1].radius )
  348. {
  349. centers[j][k] = centers[j][k-1];
  350. k--;
  351. }
  352. if (params.collectContours)
  353. {
  354. if (curCenters[i].confidence > centers[j][k].confidence
  355. || (curCenters[i].confidence == centers[j][k].confidence && curMomentss[i].m00 > momentss[j].m00))
  356. {
  357. blobContours[j] = curContours[i];
  358. momentss[j] = curMomentss[i];
  359. }
  360. }
  361. centers[j][k] = curCenters[i];
  362. break;
  363. }
  364. }
  365. if (isNew)
  366. {
  367. newCenters.push_back(std::vector<Center> (1, curCenters[i]));
  368. if (params.collectContours)
  369. {
  370. newContours.push_back(curContours[i]);
  371. newMomentss.push_back(curMomentss[i]);
  372. }
  373. }
  374. }
  375. std::copy(newCenters.begin(), newCenters.end(), std::back_inserter(centers));
  376. if (params.collectContours)
  377. {
  378. std::copy(newContours.begin(), newContours.end(), std::back_inserter(blobContours));
  379. std::copy(newMomentss.begin(), newMomentss.end(), std::back_inserter(momentss));
  380. }
  381. }
  382. for (size_t i = 0; i < centers.size(); i++)
  383. {
  384. if (centers[i].size() < params.minRepeatability)
  385. continue;
  386. Point2d sumPoint(0, 0);
  387. double normalizer = 0;
  388. for (size_t j = 0; j < centers[i].size(); j++)
  389. {
  390. sumPoint += centers[i][j].confidence * centers[i][j].location;
  391. normalizer += centers[i][j].confidence;
  392. }
  393. sumPoint *= (1. / normalizer);
  394. KeyPoint kpt(sumPoint, (float)(centers[i][centers[i].size() / 2].radius) * 2.0f);
  395. keypoints.push_back(kpt);
  396. }
  397. if (!mask.empty())
  398. {
  399. if (params.collectContours)
  400. {
  401. KeyPointsFilter::runByPixelsMask2VectorPoint(keypoints, blobContours, mask.getMat());
  402. }
  403. else
  404. {
  405. KeyPointsFilter::runByPixelsMask(keypoints, mask.getMat());
  406. }
  407. }
  408. }
  409. const std::vector<std::vector<Point> >& SimpleBlobDetectorImpl::getBlobContours() const {
  410. return blobContours;
  411. }
  412. Ptr<SimpleBlobDetector> SimpleBlobDetector::create(const SimpleBlobDetector::Params& params)
  413. {
  414. SimpleBlobDetectorImpl::validateParameters(params);
  415. return makePtr<SimpleBlobDetectorImpl>(params);
  416. }
  417. String SimpleBlobDetector::getDefaultName() const
  418. {
  419. return (Feature2D::getDefaultName() + ".SimpleBlobDetector");
  420. }
  421. }