feature.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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) 2013, OpenCV Foundation, all rights reserved.
  14. // Third party copyrights are property of their respective owners.
  15. //
  16. // Redistribution and use in source and binary forms, with or without modification,
  17. // are permitted provided that the following conditions are met:
  18. //
  19. // * Redistribution's of source code must retain the above copyright notice,
  20. // this list of conditions and the following disclaimer.
  21. //
  22. // * Redistribution's in binary form must reproduce the above copyright notice,
  23. // this list of conditions and the following disclaimer in the documentation
  24. // and/or other materials provided with the distribution.
  25. //
  26. // * The name of the copyright holders may not be used to endorse or promote products
  27. // derived from this software without specific prior written permission.
  28. //
  29. // This software is provided by the copyright holders and contributors "as is" and
  30. // any express or implied warranties, including, but not limited to, the implied
  31. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  32. // In no event shall the Intel Corporation or contributors be liable for any direct,
  33. // indirect, incidental, special, exemplary, or consequential damages
  34. // (including, but not limited to, procurement of substitute goods or services;
  35. // loss of use, data, or profits; or business interruption) however caused
  36. // and on any theory of liability, whether in contract, strict liability,
  37. // or tort (including negligence or otherwise) arising in any way out of
  38. // the use of this software, even if advised of the possibility of such damage.
  39. //
  40. //M*/
  41. #ifndef __OPENCV_FEATURE_HPP__
  42. #define __OPENCV_FEATURE_HPP__
  43. #include "opencv2/core.hpp"
  44. #include "opencv2/imgproc.hpp"
  45. #include <iostream>
  46. #include <string>
  47. #include <time.h>
  48. /*
  49. * TODO This implementation is based on apps/traincascade/
  50. * TODO Changed CvHaarEvaluator based on ADABOOSTING implementation (Grabner et al.)
  51. */
  52. namespace cv {
  53. namespace detail {
  54. inline namespace tracking {
  55. //! @addtogroup tracking_detail
  56. //! @{
  57. inline namespace contrib_feature {
  58. #define FEATURES "features"
  59. #define CC_FEATURES FEATURES
  60. #define CC_FEATURE_PARAMS "featureParams"
  61. #define CC_MAX_CAT_COUNT "maxCatCount"
  62. #define CC_FEATURE_SIZE "featSize"
  63. #define CC_NUM_FEATURES "numFeat"
  64. #define CC_ISINTEGRAL "isIntegral"
  65. #define CC_RECTS "rects"
  66. #define CC_TILTED "tilted"
  67. #define CC_RECT "rect"
  68. #define LBPF_NAME "lbpFeatureParams"
  69. #define HOGF_NAME "HOGFeatureParams"
  70. #define HFP_NAME "haarFeatureParams"
  71. #define CV_HAAR_FEATURE_MAX 3
  72. #define N_BINS 9
  73. #define N_CELLS 4
  74. #define CV_SUM_OFFSETS( p0, p1, p2, p3, rect, step ) \
  75. /* (x, y) */ \
  76. (p0) = (rect).x + (step) * (rect).y; \
  77. /* (x + w, y) */ \
  78. (p1) = (rect).x + (rect).width + (step) * (rect).y; \
  79. /* (x + w, y) */ \
  80. (p2) = (rect).x + (step) * ((rect).y + (rect).height); \
  81. /* (x + w, y + h) */ \
  82. (p3) = (rect).x + (rect).width + (step) * ((rect).y + (rect).height);
  83. #define CV_TILTED_OFFSETS( p0, p1, p2, p3, rect, step ) \
  84. /* (x, y) */ \
  85. (p0) = (rect).x + (step) * (rect).y; \
  86. /* (x - h, y + h) */ \
  87. (p1) = (rect).x - (rect).height + (step) * ((rect).y + (rect).height);\
  88. /* (x + w, y + w) */ \
  89. (p2) = (rect).x + (rect).width + (step) * ((rect).y + (rect).width); \
  90. /* (x + w - h, y + w + h) */ \
  91. (p3) = (rect).x + (rect).width - (rect).height \
  92. + (step) * ((rect).y + (rect).width + (rect).height);
  93. float calcNormFactor( const Mat& sum, const Mat& sqSum );
  94. template<class Feature>
  95. void _writeFeatures( const std::vector<Feature> features, FileStorage &fs, const Mat& featureMap )
  96. {
  97. fs << FEATURES << "[";
  98. const Mat_<int>& featureMap_ = (const Mat_<int>&) featureMap;
  99. for ( int fi = 0; fi < featureMap.cols; fi++ )
  100. if( featureMap_( 0, fi ) >= 0 )
  101. {
  102. fs << "{";
  103. features[fi].write( fs );
  104. fs << "}";
  105. }
  106. fs << "]";
  107. }
  108. class CvParams
  109. {
  110. public:
  111. CvParams();
  112. virtual ~CvParams()
  113. {
  114. }
  115. // from|to file
  116. virtual void write( FileStorage &fs ) const = 0;
  117. virtual bool read( const FileNode &node ) = 0;
  118. // from|to screen
  119. virtual void printDefaults() const;
  120. virtual void printAttrs() const;
  121. virtual bool scanAttr( const std::string prmName, const std::string val );
  122. std::string name;
  123. };
  124. class CvFeatureParams : public CvParams
  125. {
  126. public:
  127. enum FeatureType
  128. {
  129. HAAR = 0,
  130. LBP = 1,
  131. HOG = 2
  132. };
  133. CvFeatureParams();
  134. virtual void init( const CvFeatureParams& fp );
  135. virtual void write( FileStorage &fs ) const CV_OVERRIDE;
  136. virtual bool read( const FileNode &node ) CV_OVERRIDE;
  137. static Ptr<CvFeatureParams> create(CvFeatureParams::FeatureType featureType);
  138. int maxCatCount; // 0 in case of numerical features
  139. int featSize; // 1 in case of simple features (HAAR, LBP) and N_BINS(9)*N_CELLS(4) in case of Dalal's HOG features
  140. int numFeatures;
  141. };
  142. class CvFeatureEvaluator
  143. {
  144. public:
  145. virtual ~CvFeatureEvaluator()
  146. {
  147. }
  148. virtual void init( const CvFeatureParams *_featureParams, int _maxSampleCount, Size _winSize );
  149. virtual void setImage( const Mat& img, uchar clsLabel, int idx );
  150. virtual void writeFeatures( FileStorage &fs, const Mat& featureMap ) const = 0;
  151. virtual float operator()( int featureIdx, int sampleIdx ) = 0;
  152. static Ptr<CvFeatureEvaluator> create(CvFeatureParams::FeatureType type);
  153. int getNumFeatures() const
  154. {
  155. return numFeatures;
  156. }
  157. int getMaxCatCount() const
  158. {
  159. return featureParams->maxCatCount;
  160. }
  161. int getFeatureSize() const
  162. {
  163. return featureParams->featSize;
  164. }
  165. const Mat& getCls() const
  166. {
  167. return cls;
  168. }
  169. float getCls( int si ) const
  170. {
  171. return cls.at<float>( si, 0 );
  172. }
  173. protected:
  174. virtual void generateFeatures() = 0;
  175. int npos, nneg;
  176. int numFeatures;
  177. Size winSize;
  178. CvFeatureParams *featureParams;
  179. Mat cls;
  180. };
  181. class CvHaarFeatureParams : public CvFeatureParams
  182. {
  183. public:
  184. CvHaarFeatureParams();
  185. virtual void init( const CvFeatureParams& fp ) CV_OVERRIDE;
  186. virtual void write( FileStorage &fs ) const CV_OVERRIDE;
  187. virtual bool read( const FileNode &node ) CV_OVERRIDE;
  188. virtual void printDefaults() const CV_OVERRIDE;
  189. virtual void printAttrs() const CV_OVERRIDE;
  190. virtual bool scanAttr( const std::string prm, const std::string val ) CV_OVERRIDE;
  191. bool isIntegral;
  192. };
  193. class CvHaarEvaluator : public CvFeatureEvaluator
  194. {
  195. public:
  196. class FeatureHaar
  197. {
  198. public:
  199. FeatureHaar( Size patchSize );
  200. bool eval( const Mat& image, Rect ROI, float* result ) const;
  201. int getNumAreas();
  202. const std::vector<float>& getWeights() const;
  203. const std::vector<Rect>& getAreas() const;
  204. void write( FileStorage ) const
  205. {
  206. }
  207. ;
  208. float getInitMean() const;
  209. float getInitSigma() const;
  210. private:
  211. int m_type;
  212. int m_numAreas;
  213. std::vector<float> m_weights;
  214. float m_initMean;
  215. float m_initSigma;
  216. void generateRandomFeature( Size imageSize );
  217. float getSum( const Mat& image, Rect imgROI ) const;
  218. std::vector<Rect> m_areas; // areas within the patch over which to compute the feature
  219. cv::Size m_initSize; // size of the patch used during training
  220. cv::Size m_curSize; // size of the patches currently under investigation
  221. float m_scaleFactorHeight; // scaling factor in vertical direction
  222. float m_scaleFactorWidth; // scaling factor in horizontal direction
  223. std::vector<Rect> m_scaleAreas; // areas after scaling
  224. std::vector<float> m_scaleWeights; // weights after scaling
  225. };
  226. virtual void init( const CvFeatureParams *_featureParams, int _maxSampleCount, Size _winSize ) CV_OVERRIDE;
  227. virtual void setImage( const Mat& img, uchar clsLabel = 0, int idx = 1 ) CV_OVERRIDE;
  228. virtual float operator()( int featureIdx, int sampleIdx ) CV_OVERRIDE;
  229. virtual void writeFeatures( FileStorage &fs, const Mat& featureMap ) const CV_OVERRIDE;
  230. void writeFeature( FileStorage &fs ) const; // for old file format
  231. const std::vector<CvHaarEvaluator::FeatureHaar>& getFeatures() const;
  232. inline CvHaarEvaluator::FeatureHaar& getFeatures( int idx )
  233. {
  234. return features[idx];
  235. }
  236. void setWinSize( Size patchSize );
  237. Size setWinSize() const;
  238. virtual void generateFeatures() CV_OVERRIDE;
  239. /**
  240. * TODO new method
  241. * \brief Overload the original generateFeatures in order to limit the number of the features
  242. * @param numFeatures Number of the features
  243. */
  244. virtual void generateFeatures( int numFeatures );
  245. protected:
  246. bool isIntegral;
  247. /* TODO Added from MIL implementation */
  248. Mat _ii_img;
  249. void compute_integral( const cv::Mat & img, std::vector<cv::Mat_<float> > & ii_imgs )
  250. {
  251. Mat ii_img;
  252. integral( img, ii_img, CV_32F );
  253. split( ii_img, ii_imgs );
  254. }
  255. std::vector<FeatureHaar> features;
  256. Mat sum; /* sum images (each row represents image) */
  257. };
  258. struct CvHOGFeatureParams : public CvFeatureParams
  259. {
  260. CvHOGFeatureParams();
  261. };
  262. class CvHOGEvaluator : public CvFeatureEvaluator
  263. {
  264. public:
  265. virtual ~CvHOGEvaluator()
  266. {
  267. }
  268. virtual void init( const CvFeatureParams *_featureParams, int _maxSampleCount, Size _winSize ) CV_OVERRIDE;
  269. virtual void setImage( const Mat& img, uchar clsLabel, int idx ) CV_OVERRIDE;
  270. virtual float operator()( int varIdx, int sampleIdx ) CV_OVERRIDE;
  271. virtual void writeFeatures( FileStorage &fs, const Mat& featureMap ) const CV_OVERRIDE;
  272. protected:
  273. virtual void generateFeatures() CV_OVERRIDE;
  274. virtual void integralHistogram( const Mat &img, std::vector<Mat> &histogram, Mat &norm, int nbins ) const;
  275. class Feature
  276. {
  277. public:
  278. Feature();
  279. Feature( int offset, int x, int y, int cellW, int cellH );
  280. float calc( const std::vector<Mat> &_hists, const Mat &_normSum, size_t y, int featComponent ) const;
  281. void write( FileStorage &fs ) const;
  282. void write( FileStorage &fs, int varIdx ) const;
  283. Rect rect[N_CELLS]; //cells
  284. struct
  285. {
  286. int p0, p1, p2, p3;
  287. } fastRect[N_CELLS];
  288. };
  289. std::vector<Feature> features;
  290. Mat normSum; //for nomalization calculation (L1 or L2)
  291. std::vector<Mat> hist;
  292. };
  293. inline float CvHOGEvaluator::operator()( int varIdx, int sampleIdx )
  294. {
  295. int featureIdx = varIdx / ( N_BINS * N_CELLS );
  296. int componentIdx = varIdx % ( N_BINS * N_CELLS );
  297. //return features[featureIdx].calc( hist, sampleIdx, componentIdx);
  298. return features[featureIdx].calc( hist, normSum, sampleIdx, componentIdx );
  299. }
  300. inline float CvHOGEvaluator::Feature::calc( const std::vector<Mat>& _hists, const Mat& _normSum, size_t y, int featComponent ) const
  301. {
  302. float normFactor;
  303. float res;
  304. int binIdx = featComponent % N_BINS;
  305. int cellIdx = featComponent / N_BINS;
  306. const float *phist = _hists[binIdx].ptr<float>( (int) y );
  307. res = phist[fastRect[cellIdx].p0] - phist[fastRect[cellIdx].p1] - phist[fastRect[cellIdx].p2] + phist[fastRect[cellIdx].p3];
  308. const float *pnormSum = _normSum.ptr<float>( (int) y );
  309. normFactor = (float) ( pnormSum[fastRect[0].p0] - pnormSum[fastRect[1].p1] - pnormSum[fastRect[2].p2] + pnormSum[fastRect[3].p3] );
  310. res = ( res > 0.001f ) ? ( res / ( normFactor + 0.001f ) ) : 0.f; //for cutting negative values, which apper due to floating precision
  311. return res;
  312. }
  313. struct CvLBPFeatureParams : CvFeatureParams
  314. {
  315. CvLBPFeatureParams();
  316. };
  317. class CvLBPEvaluator : public CvFeatureEvaluator
  318. {
  319. public:
  320. virtual ~CvLBPEvaluator() CV_OVERRIDE
  321. {
  322. }
  323. virtual void init( const CvFeatureParams *_featureParams, int _maxSampleCount, Size _winSize ) CV_OVERRIDE;
  324. virtual void setImage( const Mat& img, uchar clsLabel, int idx ) CV_OVERRIDE;
  325. virtual float operator()( int featureIdx, int sampleIdx ) CV_OVERRIDE
  326. {
  327. return (float) features[featureIdx].calc( sum, sampleIdx );
  328. }
  329. virtual void writeFeatures( FileStorage &fs, const Mat& featureMap ) const CV_OVERRIDE;
  330. protected:
  331. virtual void generateFeatures() CV_OVERRIDE;
  332. class Feature
  333. {
  334. public:
  335. Feature();
  336. Feature( int offset, int x, int y, int _block_w, int _block_h );
  337. uchar calc( const Mat& _sum, size_t y ) const;
  338. void write( FileStorage &fs ) const;
  339. Rect rect;
  340. int p[16];
  341. };
  342. std::vector<Feature> features;
  343. Mat sum;
  344. };
  345. inline uchar CvLBPEvaluator::Feature::calc( const Mat &_sum, size_t y ) const
  346. {
  347. const int* psum = _sum.ptr<int>( (int) y );
  348. int cval = psum[p[5]] - psum[p[6]] - psum[p[9]] + psum[p[10]];
  349. return (uchar) ( ( psum[p[0]] - psum[p[1]] - psum[p[4]] + psum[p[5]] >= cval ? 128 : 0 ) | // 0
  350. ( psum[p[1]] - psum[p[2]] - psum[p[5]] + psum[p[6]] >= cval ? 64 : 0 ) | // 1
  351. ( psum[p[2]] - psum[p[3]] - psum[p[6]] + psum[p[7]] >= cval ? 32 : 0 ) | // 2
  352. ( psum[p[6]] - psum[p[7]] - psum[p[10]] + psum[p[11]] >= cval ? 16 : 0 ) | // 5
  353. ( psum[p[10]] - psum[p[11]] - psum[p[14]] + psum[p[15]] >= cval ? 8 : 0 ) | // 8
  354. ( psum[p[9]] - psum[p[10]] - psum[p[13]] + psum[p[14]] >= cval ? 4 : 0 ) | // 7
  355. ( psum[p[8]] - psum[p[9]] - psum[p[12]] + psum[p[13]] >= cval ? 2 : 0 ) | // 6
  356. ( psum[p[4]] - psum[p[5]] - psum[p[8]] + psum[p[9]] >= cval ? 1 : 0 ) ); // 3
  357. }
  358. } // namespace
  359. //! @}
  360. }}} // namespace cv
  361. #endif