Merge pull request #2444 from ilya-lavrenov:tapi_gftt
[profile/ivi/opencv.git] / modules / imgproc / src / featureselect.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 #include "opencl_kernels.hpp"
44
45 #include <cstdio>
46 #include <vector>
47 #include <iostream>
48 #include <functional>
49
50 namespace cv
51 {
52
53 struct greaterThanPtr :
54         public std::binary_function<const float *, const float *, bool>
55 {
56     bool operator () (const float * a, const float * b) const
57     { return *a > *b; }
58 };
59
60 #ifdef HAVE_OPENCL
61
62 struct Corner
63 {
64     float val;
65     short y;
66     short x;
67
68     bool operator < (const Corner & c) const
69     {  return val > c.val; }
70 };
71
72 static bool ocl_goodFeaturesToTrack( InputArray _image, OutputArray _corners,
73                                      int maxCorners, double qualityLevel, double minDistance,
74                                      InputArray _mask, int blockSize,
75                                      bool useHarrisDetector, double harrisK )
76 {
77     UMat eig, maxEigenValue;
78     if( useHarrisDetector )
79         cornerHarris( _image, eig, blockSize, 3, harrisK );
80     else
81         cornerMinEigenVal( _image, eig, blockSize, 3 );
82
83     Size imgsize = _image.size();
84     std::vector<Corner> tmpCorners;
85     size_t total, i, j, ncorners = 0, possibleCornersCount =
86             std::max(1024, static_cast<int>(imgsize.area() * 0.1));
87     bool haveMask = !_mask.empty();
88
89     // find threshold
90     {
91         CV_Assert(eig.type() == CV_32FC1);
92         int dbsize = ocl::Device::getDefault().maxComputeUnits();
93         size_t wgs = ocl::Device::getDefault().maxWorkGroupSize();
94
95         int wgs2_aligned = 1;
96         while (wgs2_aligned < (int)wgs)
97             wgs2_aligned <<= 1;
98         wgs2_aligned >>= 1;
99
100         ocl::Kernel k("maxEigenVal", ocl::imgproc::gftt_oclsrc,
101                       format("-D OP_MAX_EIGEN_VAL -D WGS=%d -D groupnum=%d -D WGS2_ALIGNED=%d%s",
102                              (int)wgs, dbsize, wgs2_aligned, haveMask ? " -D HAVE_MASK" : ""));
103         if (k.empty())
104             return false;
105
106         UMat mask = _mask.getUMat();
107         maxEigenValue.create(1, dbsize, CV_32FC1);
108
109         ocl::KernelArg eigarg = ocl::KernelArg::ReadOnlyNoSize(eig),
110                 dbarg = ocl::KernelArg::PtrWriteOnly(maxEigenValue),
111                 maskarg = ocl::KernelArg::ReadOnlyNoSize(mask);
112
113         if (haveMask)
114             k.args(eigarg, eig.cols, (int)eig.total(), dbarg, maskarg);
115         else
116             k.args(eigarg, eig.cols, (int)eig.total(), dbarg);
117
118         size_t globalsize = dbsize * wgs;
119         if (!k.run(1, &globalsize, &wgs, false))
120             return false;
121
122         ocl::Kernel k2("maxEigenValTask", ocl::imgproc::gftt_oclsrc,
123                        format("-D OP_MAX_EIGEN_VAL -D WGS=%d -D WGS2_ALIGNED=%d -D groupnum=%d",
124                               wgs, wgs2_aligned, dbsize));
125         if (k2.empty())
126             return false;
127
128         k2.args(dbarg, (float)qualityLevel);
129
130         if (!k2.runTask(false))
131             return false;
132     }
133
134     // collect list of pointers to features - put them into temporary image
135     {
136         ocl::Kernel k("findCorners", ocl::imgproc::gftt_oclsrc,
137                       format("-D OP_FIND_CORNERS%s", haveMask ? " -D HAVE_MASK" : ""));
138         if (k.empty())
139             return false;
140
141         UMat counter(1, 1, CV_32SC1, Scalar::all(0)),
142             corners(1, (int)possibleCornersCount, CV_32FC2, Scalar::all(-1));
143         CV_Assert(sizeof(Corner) == corners.elemSize());
144
145         ocl::KernelArg eigarg = ocl::KernelArg::ReadOnlyNoSize(eig),
146                 cornersarg = ocl::KernelArg::PtrWriteOnly(corners),
147                 counterarg = ocl::KernelArg::PtrReadWrite(counter),
148                 thresholdarg = ocl::KernelArg::PtrReadOnly(maxEigenValue);
149
150         if (!haveMask)
151             k.args(eigarg, cornersarg, counterarg,
152                    eig.rows - 2, eig.cols - 2, thresholdarg,
153                    (int)possibleCornersCount);
154         else
155         {
156             UMat mask = _mask.getUMat();
157             k.args(eigarg, ocl::KernelArg::ReadOnlyNoSize(mask),
158                    cornersarg, counterarg, eig.rows - 2, eig.cols - 2,
159                    thresholdarg, (int)possibleCornersCount);
160         }
161
162         size_t globalsize[2] = { eig.cols - 2, eig.rows - 2 };
163         if (!k.run(2, globalsize, NULL, false))
164             return false;
165
166         total = std::min<size_t>(counter.getMat(ACCESS_READ).at<int>(0, 0), possibleCornersCount);
167         tmpCorners.resize(total);
168
169         Mat mcorners(1, (int)total, CV_32FC2, &tmpCorners[0]);
170         corners.colRange(0, (int)total).copyTo(mcorners);
171     }
172     std::sort(tmpCorners.begin(), tmpCorners.end());
173
174     std::vector<Point2f> corners;
175     corners.reserve(total);
176
177     if (minDistance >= 1)
178     {
179          // Partition the image into larger grids
180         int w = imgsize.width, h = imgsize.height;
181
182         const int cell_size = cvRound(minDistance);
183         const int grid_width = (w + cell_size - 1) / cell_size;
184         const int grid_height = (h + cell_size - 1) / cell_size;
185
186         std::vector<std::vector<Point2f> > grid(grid_width*grid_height);
187         minDistance *= minDistance;
188
189         for( i = 0; i < total; i++ )
190         {
191             const Corner & c = tmpCorners[i];
192             bool good = true;
193
194             int x_cell = c.x / cell_size;
195             int y_cell = c.y / cell_size;
196
197             int x1 = x_cell - 1;
198             int y1 = y_cell - 1;
199             int x2 = x_cell + 1;
200             int y2 = y_cell + 1;
201
202             // boundary check
203             x1 = std::max(0, x1);
204             y1 = std::max(0, y1);
205             x2 = std::min(grid_width - 1, x2);
206             y2 = std::min(grid_height - 1, y2);
207
208             for( int yy = y1; yy <= y2; yy++ )
209                 for( int xx = x1; xx <= x2; xx++ )
210                 {
211                     std::vector<Point2f> &m = grid[yy * grid_width + xx];
212
213                     if( m.size() )
214                     {
215                         for(j = 0; j < m.size(); j++)
216                         {
217                             float dx = c.x - m[j].x;
218                             float dy = c.y - m[j].y;
219
220                             if( dx*dx + dy*dy < minDistance )
221                             {
222                                 good = false;
223                                 goto break_out;
224                             }
225                         }
226                     }
227                 }
228
229             break_out:
230
231             if (good)
232             {
233                 grid[y_cell*grid_width + x_cell].push_back(Point2f((float)c.x, (float)c.y));
234
235                 corners.push_back(Point2f((float)c.x, (float)c.y));
236                 ++ncorners;
237
238                 if( maxCorners > 0 && (int)ncorners == maxCorners )
239                     break;
240             }
241         }
242     }
243     else
244     {
245         for( i = 0; i < total; i++ )
246         {
247             const Corner & c = tmpCorners[i];
248
249             corners.push_back(Point2f((float)c.x, (float)c.y));
250             ++ncorners;
251             if( maxCorners > 0 && (int)ncorners == maxCorners )
252                 break;
253         }
254     }
255
256     Mat(corners).convertTo(_corners, _corners.fixedType() ? _corners.type() : CV_32F);
257     return true;
258 }
259
260 #endif
261
262 }
263
264 void cv::goodFeaturesToTrack( InputArray _image, OutputArray _corners,
265                               int maxCorners, double qualityLevel, double minDistance,
266                               InputArray _mask, int blockSize,
267                               bool useHarrisDetector, double harrisK )
268 {
269     CV_Assert( qualityLevel > 0 && minDistance >= 0 && maxCorners >= 0 );
270     CV_Assert( _mask.empty() || (_mask.type() == CV_8UC1 && _mask.sameSize(_image)) );
271
272     CV_OCL_RUN(_image.dims() <= 2 && _image.isUMat(),
273                ocl_goodFeaturesToTrack(_image, _corners, maxCorners, qualityLevel, minDistance,
274                                     _mask, blockSize, useHarrisDetector, harrisK))
275
276     Mat image = _image.getMat(), eig, tmp;
277     if( useHarrisDetector )
278         cornerHarris( image, eig, blockSize, 3, harrisK );
279     else
280         cornerMinEigenVal( image, eig, blockSize, 3 );
281
282     double maxVal = 0;
283     minMaxLoc( eig, 0, &maxVal, 0, 0, _mask );
284     threshold( eig, eig, maxVal*qualityLevel, 0, THRESH_TOZERO );
285     dilate( eig, tmp, Mat());
286
287     Size imgsize = image.size();
288     std::vector<const float*> tmpCorners;
289
290     // collect list of pointers to features - put them into temporary image
291     Mat mask = _mask.getMat();
292     for( int y = 1; y < imgsize.height - 1; y++ )
293     {
294         const float* eig_data = (const float*)eig.ptr(y);
295         const float* tmp_data = (const float*)tmp.ptr(y);
296         const uchar* mask_data = mask.data ? mask.ptr(y) : 0;
297
298         for( int x = 1; x < imgsize.width - 1; x++ )
299         {
300             float val = eig_data[x];
301             if( val != 0 && val == tmp_data[x] && (!mask_data || mask_data[x]) )
302                 tmpCorners.push_back(eig_data + x);
303         }
304     }
305     std::sort( tmpCorners.begin(), tmpCorners.end(), greaterThanPtr() );
306
307     std::vector<Point2f> corners;
308     size_t i, j, total = tmpCorners.size(), ncorners = 0;
309
310     if (minDistance >= 1)
311     {
312          // Partition the image into larger grids
313         int w = image.cols;
314         int h = image.rows;
315
316         const int cell_size = cvRound(minDistance);
317         const int grid_width = (w + cell_size - 1) / cell_size;
318         const int grid_height = (h + cell_size - 1) / cell_size;
319
320         std::vector<std::vector<Point2f> > grid(grid_width*grid_height);
321
322         minDistance *= minDistance;
323
324         for( i = 0; i < total; i++ )
325         {
326             int ofs = (int)((const uchar*)tmpCorners[i] - eig.data);
327             int y = (int)(ofs / eig.step);
328             int x = (int)((ofs - y*eig.step)/sizeof(float));
329
330             bool good = true;
331
332             int x_cell = x / cell_size;
333             int y_cell = y / cell_size;
334
335             int x1 = x_cell - 1;
336             int y1 = y_cell - 1;
337             int x2 = x_cell + 1;
338             int y2 = y_cell + 1;
339
340             // boundary check
341             x1 = std::max(0, x1);
342             y1 = std::max(0, y1);
343             x2 = std::min(grid_width-1, x2);
344             y2 = std::min(grid_height-1, y2);
345
346             for( int yy = y1; yy <= y2; yy++ )
347                 for( int xx = x1; xx <= x2; xx++ )
348                 {
349                     std::vector <Point2f> &m = grid[yy*grid_width + xx];
350
351                     if( m.size() )
352                     {
353                         for(j = 0; j < m.size(); j++)
354                         {
355                             float dx = x - m[j].x;
356                             float dy = y - m[j].y;
357
358                             if( dx*dx + dy*dy < minDistance )
359                             {
360                                 good = false;
361                                 goto break_out;
362                             }
363                         }
364                     }
365                 }
366
367             break_out:
368
369             if (good)
370             {
371                 grid[y_cell*grid_width + x_cell].push_back(Point2f((float)x, (float)y));
372
373                 corners.push_back(Point2f((float)x, (float)y));
374                 ++ncorners;
375
376                 if( maxCorners > 0 && (int)ncorners == maxCorners )
377                     break;
378             }
379         }
380     }
381     else
382     {
383         for( i = 0; i < total; i++ )
384         {
385             int ofs = (int)((const uchar*)tmpCorners[i] - eig.data);
386             int y = (int)(ofs / eig.step);
387             int x = (int)((ofs - y*eig.step)/sizeof(float));
388
389             corners.push_back(Point2f((float)x, (float)y));
390             ++ncorners;
391             if( maxCorners > 0 && (int)ncorners == maxCorners )
392                 break;
393         }
394     }
395
396     Mat(corners).convertTo(_corners, _corners.fixedType() ? _corners.type() : CV_32F);
397 }
398
399 CV_IMPL void
400 cvGoodFeaturesToTrack( const void* _image, void*, void*,
401                        CvPoint2D32f* _corners, int *_corner_count,
402                        double quality_level, double min_distance,
403                        const void* _maskImage, int block_size,
404                        int use_harris, double harris_k )
405 {
406     cv::Mat image = cv::cvarrToMat(_image), mask;
407     std::vector<cv::Point2f> corners;
408
409     if( _maskImage )
410         mask = cv::cvarrToMat(_maskImage);
411
412     CV_Assert( _corners && _corner_count );
413     cv::goodFeaturesToTrack( image, corners, *_corner_count, quality_level,
414         min_distance, mask, block_size, use_harris != 0, harris_k );
415
416     size_t i, ncorners = corners.size();
417     for( i = 0; i < ncorners; i++ )
418         _corners[i] = corners[i];
419     *_corner_count = (int)ncorners;
420 }
421
422 /* End of file. */