Merge pull request #1263 from abidrahmank:pyCLAHE_24
[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 CV_WRAP void Feature2D::compute( const Mat& image, CV_OUT CV_IN_OUT std::vector<KeyPoint>& keypoints, CV_OUT Mat& descriptors ) const
111 {
112    DescriptorExtractor::compute(image, keypoints, descriptors);
113 }
114
115 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
116
117 /****************************************************************************************\
118 *                             OpponentColorDescriptorExtractor                           *
119 \****************************************************************************************/
120 OpponentColorDescriptorExtractor::OpponentColorDescriptorExtractor( const Ptr<DescriptorExtractor>& _descriptorExtractor ) :
121         descriptorExtractor(_descriptorExtractor)
122 {
123     CV_Assert( !descriptorExtractor.empty() );
124 }
125
126 static void convertBGRImageToOpponentColorSpace( const Mat& bgrImage, vector<Mat>& opponentChannels )
127 {
128     if( bgrImage.type() != CV_8UC3 )
129         CV_Error( CV_StsBadArg, "input image must be an BGR image of type CV_8UC3" );
130
131     // Prepare opponent color space storage matrices.
132     opponentChannels.resize( 3 );
133     opponentChannels[0] = cv::Mat(bgrImage.size(), CV_8UC1); // R-G RED-GREEN
134     opponentChannels[1] = cv::Mat(bgrImage.size(), CV_8UC1); // R+G-2B YELLOW-BLUE
135     opponentChannels[2] = cv::Mat(bgrImage.size(), CV_8UC1); // R+G+B
136
137     for(int y = 0; y < bgrImage.rows; ++y)
138         for(int x = 0; x < bgrImage.cols; ++x)
139         {
140             Vec3b v = bgrImage.at<Vec3b>(y, x);
141             uchar& b = v[0];
142             uchar& g = v[1];
143             uchar& r = v[2];
144
145             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
146             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
147             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
148         }
149 }
150
151 struct KP_LessThan
152 {
153     KP_LessThan(const vector<KeyPoint>& _kp) : kp(&_kp) {}
154     bool operator()(int i, int j) const
155     {
156         return (*kp)[i].class_id < (*kp)[j].class_id;
157     }
158     const vector<KeyPoint>* kp;
159 };
160
161 void OpponentColorDescriptorExtractor::computeImpl( const Mat& bgrImage, vector<KeyPoint>& keypoints, Mat& descriptors ) const
162 {
163     vector<Mat> opponentChannels;
164     convertBGRImageToOpponentColorSpace( bgrImage, opponentChannels );
165
166     const int N = 3; // channels count
167     vector<KeyPoint> channelKeypoints[N];
168     Mat channelDescriptors[N];
169     vector<int> idxs[N];
170
171     // Compute descriptors three times, once for each Opponent channel to concatenate into a single color descriptor
172     int maxKeypointsCount = 0;
173     for( int ci = 0; ci < N; ci++ )
174     {
175         channelKeypoints[ci].insert( channelKeypoints[ci].begin(), keypoints.begin(), keypoints.end() );
176         // Use class_id member to get indices into initial keypoints vector
177         for( size_t ki = 0; ki < channelKeypoints[ci].size(); ki++ )
178             channelKeypoints[ci][ki].class_id = (int)ki;
179
180         descriptorExtractor->compute( opponentChannels[ci], channelKeypoints[ci], channelDescriptors[ci] );
181         idxs[ci].resize( channelKeypoints[ci].size() );
182         for( size_t ki = 0; ki < channelKeypoints[ci].size(); ki++ )
183         {
184             idxs[ci][ki] = (int)ki;
185         }
186         std::sort( idxs[ci].begin(), idxs[ci].end(), KP_LessThan(channelKeypoints[ci]) );
187         maxKeypointsCount = std::max( maxKeypointsCount, (int)channelKeypoints[ci].size());
188     }
189
190     vector<KeyPoint> outKeypoints;
191     outKeypoints.reserve( keypoints.size() );
192
193     int dSize = descriptorExtractor->descriptorSize();
194     Mat mergedDescriptors( maxKeypointsCount, 3*dSize, descriptorExtractor->descriptorType() );
195     int mergedCount = 0;
196     // cp - current channel position
197     size_t cp[] = {0, 0, 0};
198     while( cp[0] < channelKeypoints[0].size() &&
199            cp[1] < channelKeypoints[1].size() &&
200            cp[2] < channelKeypoints[2].size() )
201     {
202         const int maxInitIdx = std::max( 0, std::max( channelKeypoints[0][idxs[0][cp[0]]].class_id,
203                                                       std::max( channelKeypoints[1][idxs[1][cp[1]]].class_id,
204                                                                 channelKeypoints[2][idxs[2][cp[2]]].class_id ) ) );
205
206         while( channelKeypoints[0][idxs[0][cp[0]]].class_id < maxInitIdx && cp[0] < channelKeypoints[0].size() ) { cp[0]++; }
207         while( channelKeypoints[1][idxs[1][cp[1]]].class_id < maxInitIdx && cp[1] < channelKeypoints[1].size() ) { cp[1]++; }
208         while( channelKeypoints[2][idxs[2][cp[2]]].class_id < maxInitIdx && cp[2] < channelKeypoints[2].size() ) { cp[2]++; }
209         if( cp[0] >= channelKeypoints[0].size() || cp[1] >= channelKeypoints[1].size() || cp[2] >= channelKeypoints[2].size() )
210             break;
211
212         if( channelKeypoints[0][idxs[0][cp[0]]].class_id == maxInitIdx &&
213             channelKeypoints[1][idxs[1][cp[1]]].class_id == maxInitIdx &&
214             channelKeypoints[2][idxs[2][cp[2]]].class_id == maxInitIdx )
215         {
216             outKeypoints.push_back( keypoints[maxInitIdx] );
217             // merge descriptors
218             for( int ci = 0; ci < N; ci++ )
219             {
220                 Mat dst = mergedDescriptors(Range(mergedCount, mergedCount+1), Range(ci*dSize, (ci+1)*dSize));
221                 channelDescriptors[ci].row( idxs[ci][cp[ci]] ).copyTo( dst );
222                 cp[ci]++;
223             }
224             mergedCount++;
225         }
226     }
227     mergedDescriptors.rowRange(0, mergedCount).copyTo( descriptors );
228     std::swap( outKeypoints, keypoints );
229 }
230
231 void OpponentColorDescriptorExtractor::read( const FileNode& fn )
232 {
233     descriptorExtractor->read(fn);
234 }
235
236 void OpponentColorDescriptorExtractor::write( FileStorage& fs ) const
237 {
238     descriptorExtractor->write(fs);
239 }
240
241 int OpponentColorDescriptorExtractor::descriptorSize() const
242 {
243     return 3*descriptorExtractor->descriptorSize();
244 }
245
246 int OpponentColorDescriptorExtractor::descriptorType() const
247 {
248     return descriptorExtractor->descriptorType();
249 }
250
251 bool OpponentColorDescriptorExtractor::empty() const
252 {
253     return descriptorExtractor.empty() || (DescriptorExtractor*)(descriptorExtractor)->empty();
254 }
255
256 }