CLAHE Python bindings
[profile/ivi/opencv.git] / modules / features2d / src / descriptors.cpp
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 //                        Intel License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000, Intel Corporation, 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 Intel Corporation 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
42 #include "precomp.hpp"
43
44 using namespace std;
45
46 namespace cv
47 {
48
49 /****************************************************************************************\
50 *                                 DescriptorExtractor                                    *
51 \****************************************************************************************/
52 /*
53  *   DescriptorExtractor
54  */
55 DescriptorExtractor::~DescriptorExtractor()
56 {}
57
58 void DescriptorExtractor::compute( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors ) const
59 {
60     if( image.empty() || keypoints.empty() )
61     {
62         descriptors.release();
63         return;
64     }
65
66     KeyPointsFilter::runByImageBorder( keypoints, image.size(), 0 );
67     KeyPointsFilter::runByKeypointSize( keypoints, std::numeric_limits<float>::epsilon() );
68
69     computeImpl( image, keypoints, descriptors );
70 }
71
72 void DescriptorExtractor::compute( const vector<Mat>& imageCollection, vector<vector<KeyPoint> >& pointCollection, vector<Mat>& descCollection ) const
73 {
74     CV_Assert( imageCollection.size() == pointCollection.size() );
75     descCollection.resize( imageCollection.size() );
76     for( size_t i = 0; i < imageCollection.size(); i++ )
77         compute( imageCollection[i], pointCollection[i], descCollection[i] );
78 }
79
80 /*void DescriptorExtractor::read( const FileNode& )
81 {}
82
83 void DescriptorExtractor::write( FileStorage& ) const
84 {}*/
85
86 bool DescriptorExtractor::empty() const
87 {
88     return false;
89 }
90
91 void DescriptorExtractor::removeBorderKeypoints( vector<KeyPoint>& keypoints,
92                                                  Size imageSize, int borderSize )
93 {
94     KeyPointsFilter::runByImageBorder( keypoints, imageSize, borderSize );
95 }
96
97 Ptr<DescriptorExtractor> DescriptorExtractor::create(const string& descriptorExtractorType)
98 {
99     if( descriptorExtractorType.find("Opponent") == 0 )
100     {
101         size_t pos = string("Opponent").size();
102         string type = descriptorExtractorType.substr(pos);
103         return new OpponentColorDescriptorExtractor(DescriptorExtractor::create(type));
104     }
105
106     return Algorithm::create<DescriptorExtractor>("Feature2D." + descriptorExtractorType);
107 }
108
109 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
110
111 /****************************************************************************************\
112 *                             OpponentColorDescriptorExtractor                           *
113 \****************************************************************************************/
114 OpponentColorDescriptorExtractor::OpponentColorDescriptorExtractor( const Ptr<DescriptorExtractor>& _descriptorExtractor ) :
115         descriptorExtractor(_descriptorExtractor)
116 {
117     CV_Assert( !descriptorExtractor.empty() );
118 }
119
120 static void convertBGRImageToOpponentColorSpace( const Mat& bgrImage, vector<Mat>& opponentChannels )
121 {
122     if( bgrImage.type() != CV_8UC3 )
123         CV_Error( CV_StsBadArg, "input image must be an BGR image of type CV_8UC3" );
124
125     // Prepare opponent color space storage matrices.
126     opponentChannels.resize( 3 );
127     opponentChannels[0] = cv::Mat(bgrImage.size(), CV_8UC1); // R-G RED-GREEN
128     opponentChannels[1] = cv::Mat(bgrImage.size(), CV_8UC1); // R+G-2B YELLOW-BLUE
129     opponentChannels[2] = cv::Mat(bgrImage.size(), CV_8UC1); // R+G+B
130
131     for(int y = 0; y < bgrImage.rows; ++y)
132         for(int x = 0; x < bgrImage.cols; ++x)
133         {
134             Vec3b v = bgrImage.at<Vec3b>(y, x);
135             uchar& b = v[0];
136             uchar& g = v[1];
137             uchar& r = v[2];
138
139             opponentChannels[0].at<uchar>(y, x) = saturate_cast<uchar>(0.5f    * (255 + g - r));       // (R - G)/sqrt(2), but converted to the destination data type
140             opponentChannels[1].at<uchar>(y, x) = saturate_cast<uchar>(0.25f   * (510 + r + g - 2*b)); // (R + G - 2B)/sqrt(6), but converted to the destination data type
141             opponentChannels[2].at<uchar>(y, x) = saturate_cast<uchar>(1.f/3.f * (r + g + b));         // (R + G + B)/sqrt(3), but converted to the destination data type
142         }
143 }
144
145 struct KP_LessThan
146 {
147     KP_LessThan(const vector<KeyPoint>& _kp) : kp(&_kp) {}
148     bool operator()(int i, int j) const
149     {
150         return (*kp)[i].class_id < (*kp)[j].class_id;
151     }
152     const vector<KeyPoint>* kp;
153 };
154
155 void OpponentColorDescriptorExtractor::computeImpl( const Mat& bgrImage, vector<KeyPoint>& keypoints, Mat& descriptors ) const
156 {
157     vector<Mat> opponentChannels;
158     convertBGRImageToOpponentColorSpace( bgrImage, opponentChannels );
159
160     const int N = 3; // channels count
161     vector<KeyPoint> channelKeypoints[N];
162     Mat channelDescriptors[N];
163     vector<int> idxs[N];
164
165     // Compute descriptors three times, once for each Opponent channel to concatenate into a single color descriptor
166     int maxKeypointsCount = 0;
167     for( int ci = 0; ci < N; ci++ )
168     {
169         channelKeypoints[ci].insert( channelKeypoints[ci].begin(), keypoints.begin(), keypoints.end() );
170         // Use class_id member to get indices into initial keypoints vector
171         for( size_t ki = 0; ki < channelKeypoints[ci].size(); ki++ )
172             channelKeypoints[ci][ki].class_id = (int)ki;
173
174         descriptorExtractor->compute( opponentChannels[ci], channelKeypoints[ci], channelDescriptors[ci] );
175         idxs[ci].resize( channelKeypoints[ci].size() );
176         for( size_t ki = 0; ki < channelKeypoints[ci].size(); ki++ )
177         {
178             idxs[ci][ki] = (int)ki;
179         }
180         std::sort( idxs[ci].begin(), idxs[ci].end(), KP_LessThan(channelKeypoints[ci]) );
181         maxKeypointsCount = std::max( maxKeypointsCount, (int)channelKeypoints[ci].size());
182     }
183
184     vector<KeyPoint> outKeypoints;
185     outKeypoints.reserve( keypoints.size() );
186
187     int dSize = descriptorExtractor->descriptorSize();
188     Mat mergedDescriptors( maxKeypointsCount, 3*dSize, descriptorExtractor->descriptorType() );
189     int mergedCount = 0;
190     // cp - current channel position
191     size_t cp[] = {0, 0, 0};
192     while( cp[0] < channelKeypoints[0].size() &&
193            cp[1] < channelKeypoints[1].size() &&
194            cp[2] < channelKeypoints[2].size() )
195     {
196         const int maxInitIdx = std::max( 0, std::max( channelKeypoints[0][idxs[0][cp[0]]].class_id,
197                                                       std::max( channelKeypoints[1][idxs[1][cp[1]]].class_id,
198                                                                 channelKeypoints[2][idxs[2][cp[2]]].class_id ) ) );
199
200         while( channelKeypoints[0][idxs[0][cp[0]]].class_id < maxInitIdx && cp[0] < channelKeypoints[0].size() ) { cp[0]++; }
201         while( channelKeypoints[1][idxs[1][cp[1]]].class_id < maxInitIdx && cp[1] < channelKeypoints[1].size() ) { cp[1]++; }
202         while( channelKeypoints[2][idxs[2][cp[2]]].class_id < maxInitIdx && cp[2] < channelKeypoints[2].size() ) { cp[2]++; }
203         if( cp[0] >= channelKeypoints[0].size() || cp[1] >= channelKeypoints[1].size() || cp[2] >= channelKeypoints[2].size() )
204             break;
205
206         if( channelKeypoints[0][idxs[0][cp[0]]].class_id == maxInitIdx &&
207             channelKeypoints[1][idxs[1][cp[1]]].class_id == maxInitIdx &&
208             channelKeypoints[2][idxs[2][cp[2]]].class_id == maxInitIdx )
209         {
210             outKeypoints.push_back( keypoints[maxInitIdx] );
211             // merge descriptors
212             for( int ci = 0; ci < N; ci++ )
213             {
214                 Mat dst = mergedDescriptors(Range(mergedCount, mergedCount+1), Range(ci*dSize, (ci+1)*dSize));
215                 channelDescriptors[ci].row( idxs[ci][cp[ci]] ).copyTo( dst );
216                 cp[ci]++;
217             }
218             mergedCount++;
219         }
220     }
221     mergedDescriptors.rowRange(0, mergedCount).copyTo( descriptors );
222     std::swap( outKeypoints, keypoints );
223 }
224
225 void OpponentColorDescriptorExtractor::read( const FileNode& fn )
226 {
227     descriptorExtractor->read(fn);
228 }
229
230 void OpponentColorDescriptorExtractor::write( FileStorage& fs ) const
231 {
232     descriptorExtractor->write(fs);
233 }
234
235 int OpponentColorDescriptorExtractor::descriptorSize() const
236 {
237     return 3*descriptorExtractor->descriptorSize();
238 }
239
240 int OpponentColorDescriptorExtractor::descriptorType() const
241 {
242     return descriptorExtractor->descriptorType();
243 }
244
245 bool OpponentColorDescriptorExtractor::empty() const
246 {
247     return descriptorExtractor.empty() || (DescriptorExtractor*)(descriptorExtractor)->empty();
248 }
249
250 }