feature.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. {
  54. //! @addtogroup tracking
  55. //! @{
  56. #define FEATURES "features"
  57. #define CC_FEATURES FEATURES
  58. #define CC_FEATURE_PARAMS "featureParams"
  59. #define CC_MAX_CAT_COUNT "maxCatCount"
  60. #define CC_FEATURE_SIZE "featSize"
  61. #define CC_NUM_FEATURES "numFeat"
  62. #define CC_ISINTEGRAL "isIntegral"
  63. #define CC_RECTS "rects"
  64. #define CC_TILTED "tilted"
  65. #define CC_RECT "rect"
  66. #define LBPF_NAME "lbpFeatureParams"
  67. #define HOGF_NAME "HOGFeatureParams"
  68. #define HFP_NAME "haarFeatureParams"
  69. #define CV_HAAR_FEATURE_MAX 3
  70. #define N_BINS 9
  71. #define N_CELLS 4
  72. #define CV_SUM_OFFSETS( p0, p1, p2, p3, rect, step ) \
  73. /* (x, y) */ \
  74. (p0) = (rect).x + (step) * (rect).y; \
  75. /* (x + w, y) */ \
  76. (p1) = (rect).x + (rect).width + (step) * (rect).y; \
  77. /* (x + w, y) */ \
  78. (p2) = (rect).x + (step) * ((rect).y + (rect).height); \
  79. /* (x + w, y + h) */ \
  80. (p3) = (rect).x + (rect).width + (step) * ((rect).y + (rect).height);
  81. #define CV_TILTED_OFFSETS( p0, p1, p2, p3, rect, step ) \
  82. /* (x, y) */ \
  83. (p0) = (rect).x + (step) * (rect).y; \
  84. /* (x - h, y + h) */ \
  85. (p1) = (rect).x - (rect).height + (step) * ((rect).y + (rect).height);\
  86. /* (x + w, y + w) */ \
  87. (p2) = (rect).x + (rect).width + (step) * ((rect).y + (rect).width); \
  88. /* (x + w - h, y + w + h) */ \
  89. (p3) = (rect).x + (rect).width - (rect).height \
  90. + (step) * ((rect).y + (rect).width + (rect).height);
  91. float calcNormFactor( const Mat& sum, const Mat& sqSum );
  92. template<class Feature>
  93. void _writeFeatures( const std::vector<Feature> features, FileStorage &fs, const Mat& featureMap )
  94. {
  95. fs << FEATURES << "[";
  96. const Mat_<int>& featureMap_ = (const Mat_<int>&) featureMap;
  97. for ( int fi = 0; fi < featureMap.cols; fi++ )
  98. if( featureMap_( 0, fi ) >= 0 )
  99. {
  100. fs << "{";
  101. features[fi].write( fs );
  102. fs << "}";
  103. }
  104. fs << "]";
  105. }
  106. class CvParams
  107. {
  108. public:
  109. CvParams();
  110. virtual ~CvParams()
  111. {
  112. }
  113. // from|to file
  114. virtual void write( FileStorage &fs ) const = 0;
  115. virtual bool read( const FileNode &node ) = 0;
  116. // from|to screen
  117. virtual void printDefaults() const;
  118. virtual void printAttrs() const;
  119. virtual bool scanAttr( const std::string prmName, const std::string val );
  120. std::string name;
  121. };
  122. class CvFeatureParams : public CvParams
  123. {
  124. public:
  125. enum FeatureType
  126. {
  127. HAAR = 0,
  128. LBP = 1,
  129. HOG = 2
  130. };
  131. CvFeatureParams();
  132. virtual void init( const CvFeatureParams& fp );
  133. virtual void write( FileStorage &fs ) const CV_OVERRIDE;
  134. virtual bool read( const FileNode &node ) CV_OVERRIDE;
  135. static Ptr<CvFeatureParams> create(CvFeatureParams::FeatureType featureType);
  136. int maxCatCount; // 0 in case of numerical features
  137. int featSize; // 1 in case of simple features (HAAR, LBP) and N_BINS(9)*N_CELLS(4) in case of Dalal's HOG features
  138. int numFeatures;
  139. };
  140. class CvFeatureEvaluator
  141. {
  142. public:
  143. virtual ~CvFeatureEvaluator()
  144. {
  145. }
  146. virtual void init( const CvFeatureParams *_featureParams, int _maxSampleCount, Size _winSize );
  147. virtual void setImage( const Mat& img, uchar clsLabel, int idx );
  148. virtual void writeFeatures( FileStorage &fs, const Mat& featureMap ) const = 0;
  149. virtual float operator()( int featureIdx, int sampleIdx ) = 0;
  150. static Ptr<CvFeatureEvaluator> create(CvFeatureParams::FeatureType type);
  151. int getNumFeatures() const
  152. {
  153. return numFeatures;
  154. }
  155. int getMaxCatCount() const
  156. {
  157. return featureParams->maxCatCount;
  158. }
  159. int getFeatureSize() const
  160. {
  161. return featureParams->featSize;
  162. }
  163. const Mat& getCls() const
  164. {
  165. return cls;
  166. }
  167. float getCls( int si ) const
  168. {
  169. return cls.at<float>( si, 0 );
  170. }
  171. protected:
  172. virtual void generateFeatures() = 0;
  173. int npos, nneg;
  174. int numFeatures;
  175. Size winSize;
  176. CvFeatureParams *featureParams;
  177. Mat cls;
  178. };
  179. class CvHaarFeatureParams : public CvFeatureParams
  180. {
  181. public:
  182. CvHaarFeatureParams();
  183. virtual void init( const CvFeatureParams& fp ) CV_OVERRIDE;
  184. virtual void write( FileStorage &fs ) const CV_OVERRIDE;
  185. virtual bool read( const FileNode &node ) CV_OVERRIDE;
  186. virtual void printDefaults() const CV_OVERRIDE;
  187. virtual void printAttrs() const CV_OVERRIDE;
  188. virtual bool scanAttr( const std::string prm, const std::string val ) CV_OVERRIDE;
  189. bool isIntegral;
  190. };
  191. class CvHaarEvaluator : public CvFeatureEvaluator
  192. {
  193. public:
  194. class FeatureHaar
  195. {
  196. public:
  197. FeatureHaar( Size patchSize );
  198. bool eval( const Mat& image, Rect ROI, float* result ) const;
  199. int getNumAreas();
  200. const std::vector<float>& getWeights() const;
  201. const std::vector<Rect>& getAreas() const;
  202. void write( FileStorage ) const
  203. {
  204. }
  205. ;
  206. float getInitMean() const;
  207. float getInitSigma() const;
  208. private:
  209. int m_type;
  210. int m_numAreas;
  211. std::vector<float> m_weights;
  212. float m_initMean;
  213. float m_initSigma;
  214. void generateRandomFeature( Size imageSize );
  215. float getSum( const Mat& image, Rect imgROI ) const;
  216. std::vector<Rect> m_areas; // areas within the patch over which to compute the feature
  217. cv::Size m_initSize; // size of the patch used during training
  218. cv::Size m_curSize; // size of the patches currently under investigation
  219. float m_scaleFactorHeight; // scaling factor in vertical direction
  220. float m_scaleFactorWidth; // scaling factor in horizontal direction
  221. std::vector<Rect> m_scaleAreas; // areas after scaling
  222. std::vector<float> m_scaleWeights; // weights after scaling
  223. };
  224. virtual void init( const CvFeatureParams *_featureParams, int _maxSampleCount, Size _winSize ) CV_OVERRIDE;
  225. virtual void setImage( const Mat& img, uchar clsLabel = 0, int idx = 1 ) CV_OVERRIDE;
  226. virtual float operator()( int featureIdx, int sampleIdx ) CV_OVERRIDE;
  227. virtual void writeFeatures( FileStorage &fs, const Mat& featureMap ) const CV_OVERRIDE;
  228. void writeFeature( FileStorage &fs ) const; // for old file format
  229. const std::vector<CvHaarEvaluator::FeatureHaar>& getFeatures() const;
  230. inline CvHaarEvaluator::FeatureHaar& getFeatures( int idx )
  231. {
  232. return features[idx];
  233. }
  234. void setWinSize( Size patchSize );
  235. Size setWinSize() const;
  236. virtual void generateFeatures() CV_OVERRIDE;
  237. /**
  238. * TODO new method
  239. * \brief Overload the original generateFeatures in order to limit the number of the features
  240. * @param numFeatures Number of the features
  241. */
  242. virtual void generateFeatures( int numFeatures );
  243. protected:
  244. bool isIntegral;
  245. /* TODO Added from MIL implementation */
  246. Mat _ii_img;
  247. void compute_integral( const cv::Mat & img, std::vector<cv::Mat_<float> > & ii_imgs )
  248. {
  249. Mat ii_img;
  250. integral( img, ii_img, CV_32F );
  251. split( ii_img, ii_imgs );
  252. }
  253. std::vector<FeatureHaar> features;
  254. Mat sum; /* sum images (each row represents image) */
  255. };
  256. struct CvHOGFeatureParams : public CvFeatureParams
  257. {
  258. CvHOGFeatureParams();
  259. };
  260. class CvHOGEvaluator : public CvFeatureEvaluator
  261. {
  262. public:
  263. virtual ~CvHOGEvaluator()
  264. {
  265. }
  266. virtual void init( const CvFeatureParams *_featureParams, int _maxSampleCount, Size _winSize ) CV_OVERRIDE;
  267. virtual void setImage( const Mat& img, uchar clsLabel, int idx ) CV_OVERRIDE;
  268. virtual float operator()( int varIdx, int sampleIdx ) CV_OVERRIDE;
  269. virtual void writeFeatures( FileStorage &fs, const Mat& featureMap ) const CV_OVERRIDE;
  270. protected:
  271. virtual void generateFeatures() CV_OVERRIDE;
  272. virtual void integralHistogram( const Mat &img, std::vector<Mat> &histogram, Mat &norm, int nbins ) const;
  273. class Feature
  274. {
  275. public:
  276. Feature();
  277. Feature( int offset, int x, int y, int cellW, int cellH );
  278. float calc( const std::vector<Mat> &_hists, const Mat &_normSum, size_t y, int featComponent ) const;
  279. void write( FileStorage &fs ) const;
  280. void write( FileStorage &fs, int varIdx ) const;
  281. Rect rect[N_CELLS]; //cells
  282. struct
  283. {
  284. int p0, p1, p2, p3;
  285. } fastRect[N_CELLS];
  286. };
  287. std::vector<Feature> features;
  288. Mat normSum; //for nomalization calculation (L1 or L2)
  289. std::vector<Mat> hist;
  290. };
  291. inline float CvHOGEvaluator::operator()( int varIdx, int sampleIdx )
  292. {
  293. int featureIdx = varIdx / ( N_BINS * N_CELLS );
  294. int componentIdx = varIdx % ( N_BINS * N_CELLS );
  295. //return features[featureIdx].calc( hist, sampleIdx, componentIdx);
  296. return features[featureIdx].calc( hist, normSum, sampleIdx, componentIdx );
  297. }
  298. inline float CvHOGEvaluator::Feature::calc( const std::vector<Mat>& _hists, const Mat& _normSum, size_t y, int featComponent ) const
  299. {
  300. float normFactor;
  301. float res;
  302. int binIdx = featComponent % N_BINS;
  303. int cellIdx = featComponent / N_BINS;
  304. const float *phist = _hists[binIdx].ptr<float>( (int) y );
  305. res = phist[fastRect[cellIdx].p0] - phist[fastRect[cellIdx].p1] - phist[fastRect[cellIdx].p2] + phist[fastRect[cellIdx].p3];
  306. const float *pnormSum = _normSum.ptr<float>( (int) y );
  307. normFactor = (float) ( pnormSum[fastRect[0].p0] - pnormSum[fastRect[1].p1] - pnormSum[fastRect[2].p2] + pnormSum[fastRect[3].p3] );
  308. res = ( res > 0.001f ) ? ( res / ( normFactor + 0.001f ) ) : 0.f; //for cutting negative values, which apper due to floating precision
  309. return res;
  310. }
  311. struct CvLBPFeatureParams : CvFeatureParams
  312. {
  313. CvLBPFeatureParams();
  314. };
  315. class CvLBPEvaluator : public CvFeatureEvaluator
  316. {
  317. public:
  318. virtual ~CvLBPEvaluator() CV_OVERRIDE
  319. {
  320. }
  321. virtual void init( const CvFeatureParams *_featureParams, int _maxSampleCount, Size _winSize ) CV_OVERRIDE;
  322. virtual void setImage( const Mat& img, uchar clsLabel, int idx ) CV_OVERRIDE;
  323. virtual float operator()( int featureIdx, int sampleIdx ) CV_OVERRIDE
  324. {
  325. return (float) features[featureIdx].calc( sum, sampleIdx );
  326. }
  327. virtual void writeFeatures( FileStorage &fs, const Mat& featureMap ) const CV_OVERRIDE;
  328. protected:
  329. virtual void generateFeatures() CV_OVERRIDE;
  330. class Feature
  331. {
  332. public:
  333. Feature();
  334. Feature( int offset, int x, int y, int _block_w, int _block_h );
  335. uchar calc( const Mat& _sum, size_t y ) const;
  336. void write( FileStorage &fs ) const;
  337. Rect rect;
  338. int p[16];
  339. };
  340. std::vector<Feature> features;
  341. Mat sum;
  342. };
  343. inline uchar CvLBPEvaluator::Feature::calc( const Mat &_sum, size_t y ) const
  344. {
  345. const int* psum = _sum.ptr<int>( (int) y );
  346. int cval = psum[p[5]] - psum[p[6]] - psum[p[9]] + psum[p[10]];
  347. return (uchar) ( ( psum[p[0]] - psum[p[1]] - psum[p[4]] + psum[p[5]] >= cval ? 128 : 0 ) | // 0
  348. ( psum[p[1]] - psum[p[2]] - psum[p[5]] + psum[p[6]] >= cval ? 64 : 0 ) | // 1
  349. ( psum[p[2]] - psum[p[3]] - psum[p[6]] + psum[p[7]] >= cval ? 32 : 0 ) | // 2
  350. ( psum[p[6]] - psum[p[7]] - psum[p[10]] + psum[p[11]] >= cval ? 16 : 0 ) | // 5
  351. ( psum[p[10]] - psum[p[11]] - psum[p[14]] + psum[p[15]] >= cval ? 8 : 0 ) | // 8
  352. ( psum[p[9]] - psum[p[10]] - psum[p[13]] + psum[p[14]] >= cval ? 4 : 0 ) | // 7
  353. ( psum[p[8]] - psum[p[9]] - psum[p[12]] + psum[p[13]] >= cval ? 2 : 0 ) | // 6
  354. ( psum[p[4]] - psum[p[5]] - psum[p[8]] + psum[p[9]] >= cval ? 1 : 0 ) ); // 3
  355. }
  356. //! @}
  357. } /* namespace cv */
  358. #endif