blob: 71529064862ad8c855d1afeabedbc6da28081055 [file] [log] [blame]
Brian Silvermanf1196122020-01-16 00:41:54 -08001// clang-format off
2/*M///////////////////////////////////////////////////////////////////////////////////////
3//
4// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5//
6// By downloading, copying, installing or using the software you agree to this license.
7// If you do not agree to this license, do not download, install,
8// copy or use the software.
9//
10//
11// License Agreement
12// For Open Source Computer Vision Library
13//
14// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
15// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
16// Third party copyrights are property of their respective owners.
17//
18// Redistribution and use in source and binary forms, with or without modification,
19// are permitted provided that the following conditions are met:
20//
21// * Redistribution's of source code must retain the above copyright notice,
22// this list of conditions and the following disclaimer.
23//
24// * Redistribution's in binary form must reproduce the above copyright notice,
25// this list of conditions and the following disclaimer in the documentation
26// and/or other materials provided with the distribution.
27//
28// * The name of the copyright holders may not be used to endorse or promote products
29// derived from this software without specific prior written permission.
30//
31// This software is provided by the copyright holders and contributors "as is" and
32// any express or implied warranties, including, but not limited to, the implied
33// warranties of merchantability and fitness for a particular purpose are disclaimed.
34// In no event shall the Intel Corporation or contributors be liable for any direct,
35// indirect, incidental, special, exemplary, or consequential damages
36// (including, but not limited to, procurement of substitute goods or services;
37// loss of use, data, or profits; or business interruption) however caused
38// and on any theory of liability, whether in contract, strict liability,
39// or tort (including negligence or otherwise) arising in any way out of
40// the use of this software, even if advised of the possibility of such damage.
41//
42//M*/
43
44/**********************************************************************************************\
45 Implementation of SIFT is based on the code from http://blogs.oregonstate.edu/hess/code/sift/
46 Below is the original copyright.
47
48// Copyright (c) 2006-2010, Rob Hess <hess@eecs.oregonstate.edu>
49// All rights reserved.
50
51// The following patent has been issued for methods embodied in this
52// software: "Method and apparatus for identifying scale invariant features
53// in an image and use of same for locating an object in an image," David
54// G. Lowe, US Patent 6,711,293 (March 23, 2004). Provisional application
55// filed March 8, 1999. Asignee: The University of British Columbia. For
56// further details, contact David Lowe (lowe@cs.ubc.ca) or the
57// University-Industry Liaison Office of the University of British
58// Columbia.
59
60// Note that restrictions imposed by this patent (and possibly others)
61// exist independently of and may be in conflict with the freedoms granted
62// in this license, which refers to copyright of the program, not patents
63// for any methods that it implements. Both copyright and patent law must
64// be obeyed to legally use and redistribute this program and it is not the
65// purpose of this license to induce you to infringe any patents or other
66// property right claims or to contest validity of any such claims. If you
67// redistribute or use the program, then this license merely protects you
68// from committing copyright infringement. It does not protect you from
69// committing patent infringement. So, before you do anything with this
70// program, make sure that you have permission to do so not merely in terms
71// of copyright, but also in terms of patent law.
72
73// Please note that this license is not to be understood as a guarantee
74// either. If you use the program according to this license, but in
75// conflict with patent law, it does not mean that the licensor will refund
76// you for any losses that you incur if you are sued for your patent
77// infringement.
78
79// Redistribution and use in source and binary forms, with or without
80// modification, are permitted provided that the following conditions are
81// met:
82// * Redistributions of source code must retain the above copyright and
83// patent notices, this list of conditions and the following
84// disclaimer.
85// * Redistributions in binary form must reproduce the above copyright
86// notice, this list of conditions and the following disclaimer in
87// the documentation and/or other materials provided with the
88// distribution.
89// * Neither the name of Oregon State University nor the names of its
90// contributors may be used to endorse or promote products derived
91// from this software without specific prior written permission.
92
93// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
94// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
95// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
96// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
97// HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
98// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
99// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
100// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
101// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
102// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
103// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
104\**********************************************************************************************/
105// clang-format on
106
107#include "y2020/vision/sift/sift971.h"
108
109#include <iostream>
110#include <mutex>
111#include <stdarg.h>
112#include <opencv2/core/hal/hal.hpp>
113#include <opencv2/imgproc.hpp>
Brian Silverman3fec6482020-01-19 17:56:20 -0800114#include "glog/logging.h"
115
116#include "y2020/vision/sift/fast_gaussian.h"
Brian Silvermanf1196122020-01-16 00:41:54 -0800117
118using namespace cv;
119
120namespace frc971 {
121namespace vision {
122namespace {
123
124#define USE_AVX2 0
125
126/******************************* Defs and macros *****************************/
127
128// default width of descriptor histogram array
129static const int SIFT_DESCR_WIDTH = 4;
130
131// default number of bins per histogram in descriptor array
132static const int SIFT_DESCR_HIST_BINS = 8;
133
134// assumed gaussian blur for input image
135static const float SIFT_INIT_SIGMA = 0.5f;
136
137// width of border in which to ignore keypoints
138static const int SIFT_IMG_BORDER = 5;
139
140// maximum steps of keypoint interpolation before failure
141static const int SIFT_MAX_INTERP_STEPS = 5;
142
143// default number of bins in histogram for orientation assignment
144static const int SIFT_ORI_HIST_BINS = 36;
145
146// determines gaussian sigma for orientation assignment
147static const float SIFT_ORI_SIG_FCTR = 1.5f;
148
149// determines the radius of the region used in orientation assignment
150static const float SIFT_ORI_RADIUS = 3 * SIFT_ORI_SIG_FCTR;
151
152// orientation magnitude relative to max that results in new feature
153static const float SIFT_ORI_PEAK_RATIO = 0.8f;
154
155// determines the size of a single descriptor orientation histogram
156static const float SIFT_DESCR_SCL_FCTR = 3.f;
157
158// threshold on magnitude of elements of descriptor vector
159static const float SIFT_DESCR_MAG_THR = 0.2f;
160
161// factor used to convert floating-point descriptor to unsigned char
162static const float SIFT_INT_DESCR_FCTR = 512.f;
163
Brian Silverman3fec6482020-01-19 17:56:20 -0800164#define DoG_TYPE_SHORT 1
Brian Silvermanf1196122020-01-16 00:41:54 -0800165#if DoG_TYPE_SHORT
166// intermediate type used for DoG pyramids
167typedef short sift_wt;
168static const int SIFT_FIXPT_SCALE = 48;
169#else
170// intermediate type used for DoG pyramids
171typedef float sift_wt;
172static const int SIFT_FIXPT_SCALE = 1;
173#endif
174
175static inline void unpackOctave(const KeyPoint &kpt, int &octave, int &layer,
176 float &scale) {
177 octave = kpt.octave & 255;
178 layer = (kpt.octave >> 8) & 255;
179 octave = octave < 128 ? octave : (-128 | octave);
180 scale = octave >= 0 ? 1.f / (1 << octave) : (float)(1 << -octave);
181}
182
Brian Silverman3fec6482020-01-19 17:56:20 -0800183constexpr bool kLogTiming = false;
Brian Silvermanf1196122020-01-16 00:41:54 -0800184
185} // namespace
186
187void SIFT971_Impl::buildGaussianPyramid(const Mat &base, std::vector<Mat> &pyr,
188 int nOctaves) const {
189 std::vector<double> sig(nOctaveLayers + 3);
190 pyr.resize(nOctaves * (nOctaveLayers + 3));
191
192 // precompute Gaussian sigmas using the following formula:
193 // \sigma_{total}^2 = \sigma_{i}^2 + \sigma_{i-1}^2
194 sig[0] = sigma;
195 double k = std::pow(2., 1. / nOctaveLayers);
196 for (int i = 1; i < nOctaveLayers + 3; i++) {
197 double sig_prev = std::pow(k, (double)(i - 1)) * sigma;
198 double sig_total = sig_prev * k;
199 sig[i] = std::sqrt(sig_total * sig_total - sig_prev * sig_prev);
200 }
201
202 for (int o = 0; o < nOctaves; o++) {
203 for (int i = 0; i < nOctaveLayers + 3; i++) {
204 Mat &dst = pyr[o * (nOctaveLayers + 3) + i];
Brian Silverman3fec6482020-01-19 17:56:20 -0800205 if (o == 0 && i == 0) {
206 dst = base;
207 } else if (i == 0) {
208 // base of new octave is halved image from end of previous octave
Brian Silvermanf1196122020-01-16 00:41:54 -0800209 const Mat &src = pyr[(o - 1) * (nOctaveLayers + 3) + nOctaveLayers];
210 resize(src, dst, Size(src.cols / 2, src.rows / 2), 0, 0, INTER_NEAREST);
211 } else {
212 const Mat &src = pyr[o * (nOctaveLayers + 3) + i - 1];
Brian Silverman3fec6482020-01-19 17:56:20 -0800213 if (use_fast_gaussian_pyramid_) {
214 FastGaussian(src, &dst, sig[i]);
215 } else {
216 GaussianBlur(src, dst, Size(), sig[i], sig[i]);
217 }
Brian Silvermanf1196122020-01-16 00:41:54 -0800218 }
219 }
220 }
221}
222
223namespace {
224
225class buildDoGPyramidComputer : public ParallelLoopBody {
226 public:
227 buildDoGPyramidComputer(int _nOctaveLayers, const std::vector<Mat> &_gpyr,
Brian Silverman3fec6482020-01-19 17:56:20 -0800228 std::vector<Mat> &_dogpyr,
229 bool use_fast_subtract_dogpyr)
230 : nOctaveLayers(_nOctaveLayers),
231 gpyr(_gpyr),
232 dogpyr(_dogpyr),
233 use_fast_subtract_dogpyr_(use_fast_subtract_dogpyr) {}
Brian Silvermanf1196122020-01-16 00:41:54 -0800234
235 void operator()(const cv::Range &range) const override {
236 const int begin = range.start;
237 const int end = range.end;
238
239 for (int a = begin; a < end; a++) {
240 const int o = a / (nOctaveLayers + 2);
241 const int i = a % (nOctaveLayers + 2);
242
243 const Mat &src1 = gpyr[o * (nOctaveLayers + 3) + i];
244 const Mat &src2 = gpyr[o * (nOctaveLayers + 3) + i + 1];
Brian Silverman3fec6482020-01-19 17:56:20 -0800245 CHECK_EQ(a, o * (nOctaveLayers + 2) + i);
Brian Silvermanf1196122020-01-16 00:41:54 -0800246 Mat &dst = dogpyr[o * (nOctaveLayers + 2) + i];
Brian Silverman3fec6482020-01-19 17:56:20 -0800247 if (use_fast_subtract_dogpyr_) {
248 FastSubtract(src2, src1, &dst);
249 } else {
250 subtract(src2, src1, dst, noArray(), DataType<sift_wt>::type);
251 }
Brian Silvermanf1196122020-01-16 00:41:54 -0800252 }
253 }
254
255 private:
Brian Silverman3fec6482020-01-19 17:56:20 -0800256 const int nOctaveLayers;
Brian Silvermanf1196122020-01-16 00:41:54 -0800257 const std::vector<Mat> &gpyr;
258 std::vector<Mat> &dogpyr;
Brian Silverman3fec6482020-01-19 17:56:20 -0800259 const bool use_fast_subtract_dogpyr_;
Brian Silvermanf1196122020-01-16 00:41:54 -0800260};
261
262} // namespace
263
264void SIFT971_Impl::buildDoGPyramid(const std::vector<Mat> &gpyr,
265 std::vector<Mat> &dogpyr) const {
266 int nOctaves = (int)gpyr.size() / (nOctaveLayers + 3);
267 dogpyr.resize(nOctaves * (nOctaveLayers + 2));
268
Brian Silverman3fec6482020-01-19 17:56:20 -0800269#if 0
Brian Silvermanf1196122020-01-16 00:41:54 -0800270 parallel_for_(Range(0, nOctaves * (nOctaveLayers + 2)),
Brian Silverman3fec6482020-01-19 17:56:20 -0800271 buildDoGPyramidComputer(nOctaveLayers, gpyr, dogpyr, use_fast_subtract_dogpyr_));
272#else
273 buildDoGPyramidComputer(
274 nOctaveLayers, gpyr, dogpyr,
275 use_fast_subtract_dogpyr_)(Range(0, nOctaves * (nOctaveLayers + 2)));
276#endif
277}
278
279// base is the image to start with.
280// gpyr is the pyramid of gaussian blurs. This is both an output and a place
281// where we store intermediates.
282// dogpyr is the pyramid of gaussian differences which we fill out.
283// number_octaves is the number of octaves to calculate.
284void SIFT971_Impl::buildGaussianAndDifferencePyramid(
285 const cv::Mat &base, std::vector<cv::Mat> &gpyr,
286 std::vector<cv::Mat> &dogpyr, int number_octaves) const {
287 const int layers_per_octave = nOctaveLayers;
288 // We use the base (possibly after downscaling) as the first "blurred" image.
289 // Then we calculate 2 more than the number of octaves.
290 // TODO(Brian): Why are there 2 extra?
291 const int gpyr_layers_per_octave = layers_per_octave + 3;
292 // There is 1 less difference than the number of blurs.
293 const int dogpyr_layers_per_octave = gpyr_layers_per_octave - 1;
294 gpyr.resize(number_octaves * gpyr_layers_per_octave);
295 dogpyr.resize(number_octaves * dogpyr_layers_per_octave);
296
297 std::vector<double> sig(gpyr_layers_per_octave);
298 // precompute Gaussian sigmas using the following formula:
299 // \sigma_{total}^2 = \sigma_{i}^2 + \sigma_{i-1}^2
300 sig[0] = sigma;
301 double k = std::pow(2., 1. / layers_per_octave);
302 for (int i = 1; i < gpyr_layers_per_octave; i++) {
303 double sig_prev = std::pow<double>(k, i - 1) * sigma;
304 double sig_total = sig_prev * k;
305 sig[i] = std::sqrt(sig_total * sig_total - sig_prev * sig_prev);
306 }
307
308 for (int octave = 0; octave < number_octaves; octave++) {
309 // At the beginning of each octave, calculate the new base image.
310 {
311 Mat &dst = gpyr[octave * gpyr_layers_per_octave];
312 if (octave == 0) {
313 // For the first octave, it's just the base image.
314 dst = base;
315 } else {
316 // For the other octaves, it's a halved version of the end of the
317 // previous octave.
318 const Mat &src = gpyr[(octave - 1) * gpyr_layers_per_octave +
319 gpyr_layers_per_octave - 1];
320 resize(src, dst, Size(src.cols / 2, src.rows / 2), 0, 0, INTER_NEAREST);
321 }
322 }
323 // We start with layer==1 because the "first layer" is just the base image
324 // (or a downscaled version of it).
325 for (int layer = 1; layer < gpyr_layers_per_octave; layer++) {
326 // The index where the current layer starts.
327 const int layer_index = octave * gpyr_layers_per_octave + layer;
328 if (use_fast_pyramid_difference_) {
329 const Mat &input = gpyr[layer_index - 1];
330 Mat &blurred = gpyr[layer_index];
331 Mat &difference =
332 dogpyr[octave * dogpyr_layers_per_octave + (layer - 1)];
333 FastGaussianAndSubtract(input, &blurred, &difference, sig[layer]);
334 } else {
335 // First, calculate the new gaussian blur.
336 {
337 const Mat &src = gpyr[layer_index - 1];
338 Mat &dst = gpyr[layer_index];
339 if (use_fast_gaussian_pyramid_) {
340 FastGaussian(src, &dst, sig[layer]);
341 } else {
342 GaussianBlur(src, dst, Size(), sig[layer], sig[layer]);
343 }
344 }
345
346 // Then, calculate the difference from the previous one.
347 {
348 const Mat &src1 = gpyr[layer_index - 1];
349 const Mat &src2 = gpyr[layer_index];
350 Mat &dst = dogpyr[octave * dogpyr_layers_per_octave + (layer - 1)];
351 if (use_fast_subtract_dogpyr_) {
352 FastSubtract(src2, src1, &dst);
353 } else {
354 subtract(src2, src1, dst, noArray(), DataType<sift_wt>::type);
355 }
356 }
357 }
358 }
359 }
Brian Silvermanf1196122020-01-16 00:41:54 -0800360}
361
362namespace {
363
364// Computes a gradient orientation histogram at a specified pixel
365static float calcOrientationHist(const Mat &img, Point pt, int radius,
366 float sigma, float *hist, int n) {
367 int i, j, k, len = (radius * 2 + 1) * (radius * 2 + 1);
368
369 float expf_scale = -1.f / (2.f * sigma * sigma);
370 AutoBuffer<float> buf(len * 4 + n + 4);
371 float *X = buf, *Y = X + len, *Mag = X, *Ori = Y + len, *W = Ori + len;
372 float *temphist = W + len + 2;
373
374 for (i = 0; i < n; i++) temphist[i] = 0.f;
375
376 for (i = -radius, k = 0; i <= radius; i++) {
377 int y = pt.y + i;
378 if (y <= 0 || y >= img.rows - 1) continue;
379 for (j = -radius; j <= radius; j++) {
380 int x = pt.x + j;
381 if (x <= 0 || x >= img.cols - 1) continue;
382
383 float dx = (float)(img.at<sift_wt>(y, x + 1) - img.at<sift_wt>(y, x - 1));
384 float dy = (float)(img.at<sift_wt>(y - 1, x) - img.at<sift_wt>(y + 1, x));
385
386 X[k] = dx;
387 Y[k] = dy;
388 W[k] = (i * i + j * j) * expf_scale;
389 k++;
390 }
391 }
392
393 len = k;
394
395 // compute gradient values, orientations and the weights over the pixel
396 // neighborhood
397 cv::hal::exp32f(W, W, len);
398 cv::hal::fastAtan2(Y, X, Ori, len, true);
399 cv::hal::magnitude32f(X, Y, Mag, len);
400
401 k = 0;
402#if CV_AVX2
403 if (USE_AVX2) {
404 __m256 __nd360 = _mm256_set1_ps(n / 360.f);
405 __m256i __n = _mm256_set1_epi32(n);
406 int CV_DECL_ALIGNED(32) bin_buf[8];
407 float CV_DECL_ALIGNED(32) w_mul_mag_buf[8];
408 for (; k <= len - 8; k += 8) {
409 __m256i __bin =
410 _mm256_cvtps_epi32(_mm256_mul_ps(__nd360, _mm256_loadu_ps(&Ori[k])));
411
412 __bin = _mm256_sub_epi32(
413 __bin, _mm256_andnot_si256(_mm256_cmpgt_epi32(__n, __bin), __n));
414 __bin = _mm256_add_epi32(
415 __bin, _mm256_and_si256(
416 __n, _mm256_cmpgt_epi32(_mm256_setzero_si256(), __bin)));
417
418 __m256 __w_mul_mag =
419 _mm256_mul_ps(_mm256_loadu_ps(&W[k]), _mm256_loadu_ps(&Mag[k]));
420
421 _mm256_store_si256((__m256i *)bin_buf, __bin);
422 _mm256_store_ps(w_mul_mag_buf, __w_mul_mag);
423
424 temphist[bin_buf[0]] += w_mul_mag_buf[0];
425 temphist[bin_buf[1]] += w_mul_mag_buf[1];
426 temphist[bin_buf[2]] += w_mul_mag_buf[2];
427 temphist[bin_buf[3]] += w_mul_mag_buf[3];
428 temphist[bin_buf[4]] += w_mul_mag_buf[4];
429 temphist[bin_buf[5]] += w_mul_mag_buf[5];
430 temphist[bin_buf[6]] += w_mul_mag_buf[6];
431 temphist[bin_buf[7]] += w_mul_mag_buf[7];
432 }
433 }
434#endif
435 for (; k < len; k++) {
436 int bin = cvRound((n / 360.f) * Ori[k]);
437 if (bin >= n) bin -= n;
438 if (bin < 0) bin += n;
439 temphist[bin] += W[k] * Mag[k];
440 }
441
442 // smooth the histogram
443 temphist[-1] = temphist[n - 1];
444 temphist[-2] = temphist[n - 2];
445 temphist[n] = temphist[0];
446 temphist[n + 1] = temphist[1];
447
448 i = 0;
449#if CV_AVX2
450 if (USE_AVX2) {
451 __m256 __d_1_16 = _mm256_set1_ps(1.f / 16.f);
452 __m256 __d_4_16 = _mm256_set1_ps(4.f / 16.f);
453 __m256 __d_6_16 = _mm256_set1_ps(6.f / 16.f);
454 for (; i <= n - 8; i += 8) {
455#if CV_FMA3
456 __m256 __hist = _mm256_fmadd_ps(
457 _mm256_add_ps(_mm256_loadu_ps(&temphist[i - 2]),
458 _mm256_loadu_ps(&temphist[i + 2])),
459 __d_1_16,
460 _mm256_fmadd_ps(
461 _mm256_add_ps(_mm256_loadu_ps(&temphist[i - 1]),
462 _mm256_loadu_ps(&temphist[i + 1])),
463 __d_4_16,
464 _mm256_mul_ps(_mm256_loadu_ps(&temphist[i]), __d_6_16)));
465#else
466 __m256 __hist = _mm256_add_ps(
467 _mm256_mul_ps(_mm256_add_ps(_mm256_loadu_ps(&temphist[i - 2]),
468 _mm256_loadu_ps(&temphist[i + 2])),
469 __d_1_16),
470 _mm256_add_ps(
471 _mm256_mul_ps(_mm256_add_ps(_mm256_loadu_ps(&temphist[i - 1]),
472 _mm256_loadu_ps(&temphist[i + 1])),
473 __d_4_16),
474 _mm256_mul_ps(_mm256_loadu_ps(&temphist[i]), __d_6_16)));
475#endif
476 _mm256_storeu_ps(&hist[i], __hist);
477 }
478 }
479#endif
480 for (; i < n; i++) {
481 hist[i] = (temphist[i - 2] + temphist[i + 2]) * (1.f / 16.f) +
482 (temphist[i - 1] + temphist[i + 1]) * (4.f / 16.f) +
483 temphist[i] * (6.f / 16.f);
484 }
485
486 float maxval = hist[0];
487 for (i = 1; i < n; i++) maxval = std::max(maxval, hist[i]);
488
489 return maxval;
490}
491
492//
493// Interpolates a scale-space extremum's location and scale to subpixel
494// accuracy to form an image feature. Rejects features with low contrast.
495// Based on Section 4 of Lowe's paper.
496static bool adjustLocalExtrema(const std::vector<Mat> &dog_pyr, KeyPoint &kpt,
497 int octv, int &layer, int &r, int &c,
498 int nOctaveLayers, float contrastThreshold,
499 float edgeThreshold, float sigma) {
500 const float img_scale = 1.f / (255 * SIFT_FIXPT_SCALE);
501 const float deriv_scale = img_scale * 0.5f;
502 const float second_deriv_scale = img_scale;
503 const float cross_deriv_scale = img_scale * 0.25f;
504
505 float xi = 0, xr = 0, xc = 0, contr = 0;
506 int i = 0;
507
508 for (; i < SIFT_MAX_INTERP_STEPS; i++) {
509 int idx = octv * (nOctaveLayers + 2) + layer;
510 const Mat &img = dog_pyr[idx];
511 const Mat &prev = dog_pyr[idx - 1];
512 const Mat &next = dog_pyr[idx + 1];
513
514 Vec3f dD(
515 (img.at<sift_wt>(r, c + 1) - img.at<sift_wt>(r, c - 1)) * deriv_scale,
516 (img.at<sift_wt>(r + 1, c) - img.at<sift_wt>(r - 1, c)) * deriv_scale,
517 (next.at<sift_wt>(r, c) - prev.at<sift_wt>(r, c)) * deriv_scale);
518
519 float v2 = (float)img.at<sift_wt>(r, c) * 2;
520 float dxx = (img.at<sift_wt>(r, c + 1) + img.at<sift_wt>(r, c - 1) - v2) *
521 second_deriv_scale;
522 float dyy = (img.at<sift_wt>(r + 1, c) + img.at<sift_wt>(r - 1, c) - v2) *
523 second_deriv_scale;
524 float dss = (next.at<sift_wt>(r, c) + prev.at<sift_wt>(r, c) - v2) *
525 second_deriv_scale;
526 float dxy =
527 (img.at<sift_wt>(r + 1, c + 1) - img.at<sift_wt>(r + 1, c - 1) -
528 img.at<sift_wt>(r - 1, c + 1) + img.at<sift_wt>(r - 1, c - 1)) *
529 cross_deriv_scale;
530 float dxs = (next.at<sift_wt>(r, c + 1) - next.at<sift_wt>(r, c - 1) -
531 prev.at<sift_wt>(r, c + 1) + prev.at<sift_wt>(r, c - 1)) *
532 cross_deriv_scale;
533 float dys = (next.at<sift_wt>(r + 1, c) - next.at<sift_wt>(r - 1, c) -
534 prev.at<sift_wt>(r + 1, c) + prev.at<sift_wt>(r - 1, c)) *
535 cross_deriv_scale;
536
537 Matx33f H(dxx, dxy, dxs, dxy, dyy, dys, dxs, dys, dss);
538
539 Vec3f X = H.solve(dD, DECOMP_LU);
540
541 xi = -X[2];
542 xr = -X[1];
543 xc = -X[0];
544
545 if (std::abs(xi) < 0.5f && std::abs(xr) < 0.5f && std::abs(xc) < 0.5f)
546 break;
547
548 if (std::abs(xi) > (float)(INT_MAX / 3) ||
549 std::abs(xr) > (float)(INT_MAX / 3) ||
550 std::abs(xc) > (float)(INT_MAX / 3))
551 return false;
552
553 c += cvRound(xc);
554 r += cvRound(xr);
555 layer += cvRound(xi);
556
557 if (layer < 1 || layer > nOctaveLayers || c < SIFT_IMG_BORDER ||
558 c >= img.cols - SIFT_IMG_BORDER || r < SIFT_IMG_BORDER ||
559 r >= img.rows - SIFT_IMG_BORDER)
560 return false;
561 }
562
563 // ensure convergence of interpolation
564 if (i >= SIFT_MAX_INTERP_STEPS) return false;
565
566 {
567 int idx = octv * (nOctaveLayers + 2) + layer;
568 const Mat &img = dog_pyr[idx];
569 const Mat &prev = dog_pyr[idx - 1];
570 const Mat &next = dog_pyr[idx + 1];
571 Matx31f dD(
572 (img.at<sift_wt>(r, c + 1) - img.at<sift_wt>(r, c - 1)) * deriv_scale,
573 (img.at<sift_wt>(r + 1, c) - img.at<sift_wt>(r - 1, c)) * deriv_scale,
574 (next.at<sift_wt>(r, c) - prev.at<sift_wt>(r, c)) * deriv_scale);
575 float t = dD.dot(Matx31f(xc, xr, xi));
576
577 contr = img.at<sift_wt>(r, c) * img_scale + t * 0.5f;
578 if (std::abs(contr) * nOctaveLayers < contrastThreshold) return false;
579
580 // principal curvatures are computed using the trace and det of Hessian
581 float v2 = img.at<sift_wt>(r, c) * 2.f;
582 float dxx = (img.at<sift_wt>(r, c + 1) + img.at<sift_wt>(r, c - 1) - v2) *
583 second_deriv_scale;
584 float dyy = (img.at<sift_wt>(r + 1, c) + img.at<sift_wt>(r - 1, c) - v2) *
585 second_deriv_scale;
586 float dxy =
587 (img.at<sift_wt>(r + 1, c + 1) - img.at<sift_wt>(r + 1, c - 1) -
588 img.at<sift_wt>(r - 1, c + 1) + img.at<sift_wt>(r - 1, c - 1)) *
589 cross_deriv_scale;
590 float tr = dxx + dyy;
591 float det = dxx * dyy - dxy * dxy;
592
593 if (det <= 0 || tr * tr * edgeThreshold >=
594 (edgeThreshold + 1) * (edgeThreshold + 1) * det)
595 return false;
596 }
597
598 kpt.pt.x = (c + xc) * (1 << octv);
599 kpt.pt.y = (r + xr) * (1 << octv);
600 kpt.octave = octv + (layer << 8) + (cvRound((xi + 0.5) * 255) << 16);
601 kpt.size = sigma * powf(2.f, (layer + xi) / nOctaveLayers) * (1 << octv) * 2;
602 kpt.response = std::abs(contr);
603
604 return true;
605}
606
607template <typename T>
608class PerThreadAccumulator {
609 public:
610 void Add(std::vector<T> &&data) {
611 std::unique_lock locker(mutex_);
612 result_.emplace_back(data);
613 }
614
615 std::vector<std::vector<T>> move_result() { return std::move(result_); }
616
617 private:
618 // Should we do something more intelligent with per-thread std::vector that we
619 // merge at the end?
620 std::vector<std::vector<T>> result_;
621 std::mutex mutex_;
622};
623
624class findScaleSpaceExtremaComputer : public ParallelLoopBody {
625 public:
626 findScaleSpaceExtremaComputer(
627 int _o, int _i, int _threshold, int _idx, int _step, int _cols,
628 int _nOctaveLayers, double _contrastThreshold, double _edgeThreshold,
629 double _sigma, const std::vector<Mat> &_gauss_pyr,
630 const std::vector<Mat> &_dog_pyr,
631 PerThreadAccumulator<KeyPoint> &_tls_kpts_struct)
632
633 : o(_o),
634 i(_i),
635 threshold(_threshold),
636 idx(_idx),
637 step(_step),
638 cols(_cols),
639 nOctaveLayers(_nOctaveLayers),
640 contrastThreshold(_contrastThreshold),
641 edgeThreshold(_edgeThreshold),
642 sigma(_sigma),
643 gauss_pyr(_gauss_pyr),
644 dog_pyr(_dog_pyr),
645 tls_kpts_struct(_tls_kpts_struct) {}
646 void operator()(const cv::Range &range) const override {
647 const int begin = range.start;
648 const int end = range.end;
649
650 static const int n = SIFT_ORI_HIST_BINS;
651 float hist[n];
652
653 const Mat &img = dog_pyr[idx];
654 const Mat &prev = dog_pyr[idx - 1];
655 const Mat &next = dog_pyr[idx + 1];
656
657 std::vector<KeyPoint> tls_kpts;
658
659 KeyPoint kpt;
660 for (int r = begin; r < end; r++) {
661 const sift_wt *currptr = img.ptr<sift_wt>(r);
662 const sift_wt *prevptr = prev.ptr<sift_wt>(r);
663 const sift_wt *nextptr = next.ptr<sift_wt>(r);
664
665 for (int c = SIFT_IMG_BORDER; c < cols - SIFT_IMG_BORDER; c++) {
666 sift_wt val = currptr[c];
667
668 // find local extrema with pixel accuracy
669 if (std::abs(val) > threshold &&
670 ((val > 0 && val >= currptr[c - 1] && val >= currptr[c + 1] &&
671 val >= currptr[c - step - 1] && val >= currptr[c - step] &&
672 val >= currptr[c - step + 1] && val >= currptr[c + step - 1] &&
673 val >= currptr[c + step] && val >= currptr[c + step + 1] &&
674 val >= nextptr[c] && val >= nextptr[c - 1] &&
675 val >= nextptr[c + 1] && val >= nextptr[c - step - 1] &&
676 val >= nextptr[c - step] && val >= nextptr[c - step + 1] &&
677 val >= nextptr[c + step - 1] && val >= nextptr[c + step] &&
678 val >= nextptr[c + step + 1] && val >= prevptr[c] &&
679 val >= prevptr[c - 1] && val >= prevptr[c + 1] &&
680 val >= prevptr[c - step - 1] && val >= prevptr[c - step] &&
681 val >= prevptr[c - step + 1] && val >= prevptr[c + step - 1] &&
682 val >= prevptr[c + step] && val >= prevptr[c + step + 1]) ||
683 (val < 0 && val <= currptr[c - 1] && val <= currptr[c + 1] &&
684 val <= currptr[c - step - 1] && val <= currptr[c - step] &&
685 val <= currptr[c - step + 1] && val <= currptr[c + step - 1] &&
686 val <= currptr[c + step] && val <= currptr[c + step + 1] &&
687 val <= nextptr[c] && val <= nextptr[c - 1] &&
688 val <= nextptr[c + 1] && val <= nextptr[c - step - 1] &&
689 val <= nextptr[c - step] && val <= nextptr[c - step + 1] &&
690 val <= nextptr[c + step - 1] && val <= nextptr[c + step] &&
691 val <= nextptr[c + step + 1] && val <= prevptr[c] &&
692 val <= prevptr[c - 1] && val <= prevptr[c + 1] &&
693 val <= prevptr[c - step - 1] && val <= prevptr[c - step] &&
694 val <= prevptr[c - step + 1] && val <= prevptr[c + step - 1] &&
695 val <= prevptr[c + step] && val <= prevptr[c + step + 1]))) {
696 int r1 = r, c1 = c, layer = i;
697 if (!adjustLocalExtrema(dog_pyr, kpt, o, layer, r1, c1, nOctaveLayers,
698 (float)contrastThreshold,
699 (float)edgeThreshold, (float)sigma))
700 continue;
701 float scl_octv = kpt.size * 0.5f / (1 << o);
702 float omax = calcOrientationHist(
703 gauss_pyr[o * (nOctaveLayers + 3) + layer], Point(c1, r1),
704 cvRound(SIFT_ORI_RADIUS * scl_octv), SIFT_ORI_SIG_FCTR * scl_octv,
705 hist, n);
706 float mag_thr = (float)(omax * SIFT_ORI_PEAK_RATIO);
707 for (int j = 0; j < n; j++) {
708 int l = j > 0 ? j - 1 : n - 1;
709 int r2 = j < n - 1 ? j + 1 : 0;
710
711 if (hist[j] > hist[l] && hist[j] > hist[r2] && hist[j] >= mag_thr) {
712 float bin = j + 0.5f * (hist[l] - hist[r2]) /
713 (hist[l] - 2 * hist[j] + hist[r2]);
714 bin = bin < 0 ? n + bin : bin >= n ? bin - n : bin;
715 kpt.angle = 360.f - (float)((360.f / n) * bin);
716 if (std::abs(kpt.angle - 360.f) < FLT_EPSILON) kpt.angle = 0.f;
717 { tls_kpts.push_back(kpt); }
718 }
719 }
720 }
721 }
722 }
723
724 tls_kpts_struct.Add(std::move(tls_kpts));
725 }
726
727 private:
728 int o, i;
729 int threshold;
730 int idx, step, cols;
731 int nOctaveLayers;
732 double contrastThreshold;
733 double edgeThreshold;
734 double sigma;
735 const std::vector<Mat> &gauss_pyr;
736 const std::vector<Mat> &dog_pyr;
737 PerThreadAccumulator<KeyPoint> &tls_kpts_struct;
738};
739
740} // namespace
741
742//
743// Detects features at extrema in DoG scale space. Bad features are discarded
744// based on contrast and ratio of principal curvatures.
745void SIFT971_Impl::findScaleSpaceExtrema(
746 const std::vector<Mat> &gauss_pyr, const std::vector<Mat> &dog_pyr,
747 std::vector<KeyPoint> &keypoints) const {
748 const int nOctaves = (int)gauss_pyr.size() / (nOctaveLayers + 3);
749 const int threshold =
750 cvFloor(0.5 * contrastThreshold / nOctaveLayers * 255 * SIFT_FIXPT_SCALE);
751
752 keypoints.clear();
753 PerThreadAccumulator<KeyPoint> tls_kpts_struct;
754
755 for (int o = 0; o < nOctaves; o++)
756 for (int i = 1; i <= nOctaveLayers; i++) {
757 const int idx = o * (nOctaveLayers + 2) + i;
758 const Mat &img = dog_pyr[idx];
759 const int step = (int)img.step1();
760 const int rows = img.rows, cols = img.cols;
761
762 parallel_for_(Range(SIFT_IMG_BORDER, rows - SIFT_IMG_BORDER),
763 findScaleSpaceExtremaComputer(
764 o, i, threshold, idx, step, cols, nOctaveLayers,
765 contrastThreshold, edgeThreshold, sigma, gauss_pyr,
766 dog_pyr, tls_kpts_struct));
767 }
768
769 const std::vector<std::vector<KeyPoint>> kpt_vecs =
770 tls_kpts_struct.move_result();
771 for (size_t i = 0; i < kpt_vecs.size(); ++i) {
772 keypoints.insert(keypoints.end(), kpt_vecs[i].begin(), kpt_vecs[i].end());
773 }
774}
775
776namespace {
777
778static void calcSIFTDescriptor(const Mat &img, Point2f ptf, float ori,
779 float scl, int d, int n, float *dst) {
780 Point pt(cvRound(ptf.x), cvRound(ptf.y));
781 float cos_t = cosf(ori * (float)(CV_PI / 180));
782 float sin_t = sinf(ori * (float)(CV_PI / 180));
783 float bins_per_rad = n / 360.f;
784 float exp_scale = -1.f / (d * d * 0.5f);
785 float hist_width = SIFT_DESCR_SCL_FCTR * scl;
786 int radius = cvRound(hist_width * 1.4142135623730951f * (d + 1) * 0.5f);
787 // Clip the radius to the diagonal of the image to avoid autobuffer too large
788 // exception
789 radius = std::min(radius, (int)sqrt(((double)img.cols) * img.cols +
790 ((double)img.rows) * img.rows));
791 cos_t /= hist_width;
792 sin_t /= hist_width;
793
794 int i, j, k, len = (radius * 2 + 1) * (radius * 2 + 1),
795 histlen = (d + 2) * (d + 2) * (n + 2);
796 int rows = img.rows, cols = img.cols;
797
798 AutoBuffer<float> buf(len * 6 + histlen);
799 float *X = buf, *Y = X + len, *Mag = Y, *Ori = Mag + len, *W = Ori + len;
800 float *RBin = W + len, *CBin = RBin + len, *hist = CBin + len;
801
802 for (i = 0; i < d + 2; i++) {
803 for (j = 0; j < d + 2; j++)
804 for (k = 0; k < n + 2; k++) hist[(i * (d + 2) + j) * (n + 2) + k] = 0.;
805 }
806
807 for (i = -radius, k = 0; i <= radius; i++)
808 for (j = -radius; j <= radius; j++) {
809 // Calculate sample's histogram array coords rotated relative to ori.
810 // Subtract 0.5 so samples that fall e.g. in the center of row 1 (i.e.
811 // r_rot = 1.5) have full weight placed in row 1 after interpolation.
812 float c_rot = j * cos_t - i * sin_t;
813 float r_rot = j * sin_t + i * cos_t;
814 float rbin = r_rot + d / 2 - 0.5f;
815 float cbin = c_rot + d / 2 - 0.5f;
816 int r = pt.y + i, c = pt.x + j;
817
818 if (rbin > -1 && rbin < d && cbin > -1 && cbin < d && r > 0 &&
819 r < rows - 1 && c > 0 && c < cols - 1) {
820 float dx =
821 (float)(img.at<sift_wt>(r, c + 1) - img.at<sift_wt>(r, c - 1));
822 float dy =
823 (float)(img.at<sift_wt>(r - 1, c) - img.at<sift_wt>(r + 1, c));
824 X[k] = dx;
825 Y[k] = dy;
826 RBin[k] = rbin;
827 CBin[k] = cbin;
828 W[k] = (c_rot * c_rot + r_rot * r_rot) * exp_scale;
829 k++;
830 }
831 }
832
833 len = k;
834 cv::hal::fastAtan2(Y, X, Ori, len, true);
835 cv::hal::magnitude32f(X, Y, Mag, len);
836 cv::hal::exp32f(W, W, len);
837
838 k = 0;
839#if CV_AVX2
840 if (USE_AVX2) {
841 int CV_DECL_ALIGNED(32) idx_buf[8];
842 float CV_DECL_ALIGNED(32) rco_buf[64];
843 const __m256 __ori = _mm256_set1_ps(ori);
844 const __m256 __bins_per_rad = _mm256_set1_ps(bins_per_rad);
845 const __m256i __n = _mm256_set1_epi32(n);
846 for (; k <= len - 8; k += 8) {
847 __m256 __rbin = _mm256_loadu_ps(&RBin[k]);
848 __m256 __cbin = _mm256_loadu_ps(&CBin[k]);
849 __m256 __obin = _mm256_mul_ps(
850 _mm256_sub_ps(_mm256_loadu_ps(&Ori[k]), __ori), __bins_per_rad);
851 __m256 __mag =
852 _mm256_mul_ps(_mm256_loadu_ps(&Mag[k]), _mm256_loadu_ps(&W[k]));
853
854 __m256 __r0 = _mm256_floor_ps(__rbin);
855 __rbin = _mm256_sub_ps(__rbin, __r0);
856 __m256 __c0 = _mm256_floor_ps(__cbin);
857 __cbin = _mm256_sub_ps(__cbin, __c0);
858 __m256 __o0 = _mm256_floor_ps(__obin);
859 __obin = _mm256_sub_ps(__obin, __o0);
860
861 __m256i __o0i = _mm256_cvtps_epi32(__o0);
862 __o0i = _mm256_add_epi32(
863 __o0i, _mm256_and_si256(
864 __n, _mm256_cmpgt_epi32(_mm256_setzero_si256(), __o0i)));
865 __o0i = _mm256_sub_epi32(
866 __o0i, _mm256_andnot_si256(_mm256_cmpgt_epi32(__n, __o0i), __n));
867
868 __m256 __v_r1 = _mm256_mul_ps(__mag, __rbin);
869 __m256 __v_r0 = _mm256_sub_ps(__mag, __v_r1);
870
871 __m256 __v_rc11 = _mm256_mul_ps(__v_r1, __cbin);
872 __m256 __v_rc10 = _mm256_sub_ps(__v_r1, __v_rc11);
873
874 __m256 __v_rc01 = _mm256_mul_ps(__v_r0, __cbin);
875 __m256 __v_rc00 = _mm256_sub_ps(__v_r0, __v_rc01);
876
877 __m256 __v_rco111 = _mm256_mul_ps(__v_rc11, __obin);
878 __m256 __v_rco110 = _mm256_sub_ps(__v_rc11, __v_rco111);
879
880 __m256 __v_rco101 = _mm256_mul_ps(__v_rc10, __obin);
881 __m256 __v_rco100 = _mm256_sub_ps(__v_rc10, __v_rco101);
882
883 __m256 __v_rco011 = _mm256_mul_ps(__v_rc01, __obin);
884 __m256 __v_rco010 = _mm256_sub_ps(__v_rc01, __v_rco011);
885
886 __m256 __v_rco001 = _mm256_mul_ps(__v_rc00, __obin);
887 __m256 __v_rco000 = _mm256_sub_ps(__v_rc00, __v_rco001);
888
889 __m256i __one = _mm256_set1_epi32(1);
890 __m256i __idx = _mm256_add_epi32(
891 _mm256_mullo_epi32(
892 _mm256_add_epi32(
893 _mm256_mullo_epi32(
894 _mm256_add_epi32(_mm256_cvtps_epi32(__r0), __one),
895 _mm256_set1_epi32(d + 2)),
896 _mm256_add_epi32(_mm256_cvtps_epi32(__c0), __one)),
897 _mm256_set1_epi32(n + 2)),
898 __o0i);
899
900 _mm256_store_si256((__m256i *)idx_buf, __idx);
901
902 _mm256_store_ps(&(rco_buf[0]), __v_rco000);
903 _mm256_store_ps(&(rco_buf[8]), __v_rco001);
904 _mm256_store_ps(&(rco_buf[16]), __v_rco010);
905 _mm256_store_ps(&(rco_buf[24]), __v_rco011);
906 _mm256_store_ps(&(rco_buf[32]), __v_rco100);
907 _mm256_store_ps(&(rco_buf[40]), __v_rco101);
908 _mm256_store_ps(&(rco_buf[48]), __v_rco110);
909 _mm256_store_ps(&(rco_buf[56]), __v_rco111);
910#define HIST_SUM_HELPER(id) \
911 hist[idx_buf[(id)]] += rco_buf[(id)]; \
912 hist[idx_buf[(id)] + 1] += rco_buf[8 + (id)]; \
913 hist[idx_buf[(id)] + (n + 2)] += rco_buf[16 + (id)]; \
914 hist[idx_buf[(id)] + (n + 3)] += rco_buf[24 + (id)]; \
915 hist[idx_buf[(id)] + (d + 2) * (n + 2)] += rco_buf[32 + (id)]; \
916 hist[idx_buf[(id)] + (d + 2) * (n + 2) + 1] += rco_buf[40 + (id)]; \
917 hist[idx_buf[(id)] + (d + 3) * (n + 2)] += rco_buf[48 + (id)]; \
918 hist[idx_buf[(id)] + (d + 3) * (n + 2) + 1] += rco_buf[56 + (id)];
919
920 HIST_SUM_HELPER(0);
921 HIST_SUM_HELPER(1);
922 HIST_SUM_HELPER(2);
923 HIST_SUM_HELPER(3);
924 HIST_SUM_HELPER(4);
925 HIST_SUM_HELPER(5);
926 HIST_SUM_HELPER(6);
927 HIST_SUM_HELPER(7);
928
929#undef HIST_SUM_HELPER
930 }
931 }
932#endif
933 for (; k < len; k++) {
934 float rbin = RBin[k], cbin = CBin[k];
935 float obin = (Ori[k] - ori) * bins_per_rad;
936 float mag = Mag[k] * W[k];
937
938 int r0 = cvFloor(rbin);
939 int c0 = cvFloor(cbin);
940 int o0 = cvFloor(obin);
941 rbin -= r0;
942 cbin -= c0;
943 obin -= o0;
944
945 if (o0 < 0) o0 += n;
946 if (o0 >= n) o0 -= n;
947
948 // histogram update using tri-linear interpolation
949 float v_r1 = mag * rbin, v_r0 = mag - v_r1;
950 float v_rc11 = v_r1 * cbin, v_rc10 = v_r1 - v_rc11;
951 float v_rc01 = v_r0 * cbin, v_rc00 = v_r0 - v_rc01;
952 float v_rco111 = v_rc11 * obin, v_rco110 = v_rc11 - v_rco111;
953 float v_rco101 = v_rc10 * obin, v_rco100 = v_rc10 - v_rco101;
954 float v_rco011 = v_rc01 * obin, v_rco010 = v_rc01 - v_rco011;
955 float v_rco001 = v_rc00 * obin, v_rco000 = v_rc00 - v_rco001;
956
957 int idx = ((r0 + 1) * (d + 2) + c0 + 1) * (n + 2) + o0;
958 hist[idx] += v_rco000;
959 hist[idx + 1] += v_rco001;
960 hist[idx + (n + 2)] += v_rco010;
961 hist[idx + (n + 3)] += v_rco011;
962 hist[idx + (d + 2) * (n + 2)] += v_rco100;
963 hist[idx + (d + 2) * (n + 2) + 1] += v_rco101;
964 hist[idx + (d + 3) * (n + 2)] += v_rco110;
965 hist[idx + (d + 3) * (n + 2) + 1] += v_rco111;
966 }
967
968 // finalize histogram, since the orientation histograms are circular
969 for (i = 0; i < d; i++)
970 for (j = 0; j < d; j++) {
971 int idx = ((i + 1) * (d + 2) + (j + 1)) * (n + 2);
972 hist[idx] += hist[idx + n];
973 hist[idx + 1] += hist[idx + n + 1];
974 for (k = 0; k < n; k++) dst[(i * d + j) * n + k] = hist[idx + k];
975 }
976 // copy histogram to the descriptor,
977 // apply hysteresis thresholding
978 // and scale the result, so that it can be easily converted
979 // to byte array
980 float nrm2 = 0;
981 len = d * d * n;
982 k = 0;
983#if CV_AVX2
984 if (USE_AVX2) {
985 float CV_DECL_ALIGNED(32) nrm2_buf[8];
986 __m256 __nrm2 = _mm256_setzero_ps();
987 __m256 __dst;
988 for (; k <= len - 8; k += 8) {
989 __dst = _mm256_loadu_ps(&dst[k]);
990#if CV_FMA3
991 __nrm2 = _mm256_fmadd_ps(__dst, __dst, __nrm2);
992#else
993 __nrm2 = _mm256_add_ps(__nrm2, _mm256_mul_ps(__dst, __dst));
994#endif
995 }
996 _mm256_store_ps(nrm2_buf, __nrm2);
997 nrm2 = nrm2_buf[0] + nrm2_buf[1] + nrm2_buf[2] + nrm2_buf[3] + nrm2_buf[4] +
998 nrm2_buf[5] + nrm2_buf[6] + nrm2_buf[7];
999 }
1000#endif
1001 for (; k < len; k++) nrm2 += dst[k] * dst[k];
1002
1003 float thr = std::sqrt(nrm2) * SIFT_DESCR_MAG_THR;
1004
1005 i = 0, nrm2 = 0;
1006#if 0 // CV_AVX2
1007 // This code cannot be enabled because it sums nrm2 in a different order,
1008 // thus producing slightly different results
1009 if( USE_AVX2 )
1010 {
1011 float CV_DECL_ALIGNED(32) nrm2_buf[8];
1012 __m256 __dst;
1013 __m256 __nrm2 = _mm256_setzero_ps();
1014 __m256 __thr = _mm256_set1_ps(thr);
1015 for( ; i <= len - 8; i += 8 )
1016 {
1017 __dst = _mm256_loadu_ps(&dst[i]);
1018 __dst = _mm256_min_ps(__dst, __thr);
1019 _mm256_storeu_ps(&dst[i], __dst);
1020#if CV_FMA3
1021 __nrm2 = _mm256_fmadd_ps(__dst, __dst, __nrm2);
1022#else
1023 __nrm2 = _mm256_add_ps(__nrm2, _mm256_mul_ps(__dst, __dst));
1024#endif
1025 }
1026 _mm256_store_ps(nrm2_buf, __nrm2);
1027 nrm2 = nrm2_buf[0] + nrm2_buf[1] + nrm2_buf[2] + nrm2_buf[3] +
1028 nrm2_buf[4] + nrm2_buf[5] + nrm2_buf[6] + nrm2_buf[7];
1029 }
1030#endif
1031 for (; i < len; i++) {
1032 float val = std::min(dst[i], thr);
1033 dst[i] = val;
1034 nrm2 += val * val;
1035 }
1036 nrm2 = SIFT_INT_DESCR_FCTR / std::max(std::sqrt(nrm2), FLT_EPSILON);
1037
1038#if 1
1039 k = 0;
1040#if CV_AVX2
1041 if (USE_AVX2) {
1042 __m256 __dst;
1043 __m256 __min = _mm256_setzero_ps();
1044 __m256 __max = _mm256_set1_ps(255.0f); // max of uchar
1045 __m256 __nrm2 = _mm256_set1_ps(nrm2);
1046 for (k = 0; k <= len - 8; k += 8) {
1047 __dst = _mm256_loadu_ps(&dst[k]);
1048 __dst = _mm256_min_ps(
1049 _mm256_max_ps(
1050 _mm256_round_ps(_mm256_mul_ps(__dst, __nrm2),
1051 _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC),
1052 __min),
1053 __max);
1054 _mm256_storeu_ps(&dst[k], __dst);
1055 }
1056 }
1057#endif
1058 for (; k < len; k++) {
1059 dst[k] = saturate_cast<uchar>(dst[k] * nrm2);
1060 }
1061#else
1062 float nrm1 = 0;
1063 for (k = 0; k < len; k++) {
1064 dst[k] *= nrm2;
1065 nrm1 += dst[k];
1066 }
1067 nrm1 = 1.f / std::max(nrm1, FLT_EPSILON);
1068 for (k = 0; k < len; k++) {
1069 dst[k] = std::sqrt(dst[k] * nrm1); // saturate_cast<uchar>(std::sqrt(dst[k]
1070 // * nrm1)*SIFT_INT_DESCR_FCTR);
1071 }
1072#endif
1073}
1074
1075class calcDescriptorsComputer : public ParallelLoopBody {
1076 public:
1077 calcDescriptorsComputer(const std::vector<Mat> &_gpyr,
1078 const std::vector<KeyPoint> &_keypoints,
1079 Mat &_descriptors, int _nOctaveLayers,
1080 int _firstOctave)
1081 : gpyr(_gpyr),
1082 keypoints(_keypoints),
1083 descriptors(_descriptors),
1084 nOctaveLayers(_nOctaveLayers),
1085 firstOctave(_firstOctave) {}
1086
1087 void operator()(const cv::Range &range) const override {
1088 const int begin = range.start;
1089 const int end = range.end;
1090
1091 static const int d = SIFT_DESCR_WIDTH, n = SIFT_DESCR_HIST_BINS;
1092
1093 for (int i = begin; i < end; i++) {
1094 KeyPoint kpt = keypoints[i];
1095 int octave, layer;
1096 float scale;
1097 unpackOctave(kpt, octave, layer, scale);
1098 CV_Assert(octave >= firstOctave && layer <= nOctaveLayers + 2);
1099 float size = kpt.size * scale;
1100 Point2f ptf(kpt.pt.x * scale, kpt.pt.y * scale);
1101 const Mat &img =
1102 gpyr[(octave - firstOctave) * (nOctaveLayers + 3) + layer];
1103
1104 float angle = 360.f - kpt.angle;
1105 if (std::abs(angle - 360.f) < FLT_EPSILON) angle = 0.f;
1106 calcSIFTDescriptor(img, ptf, angle, size * 0.5f, d, n,
1107 descriptors.ptr<float>((int)i));
1108 }
1109 }
1110
1111 private:
1112 const std::vector<Mat> &gpyr;
1113 const std::vector<KeyPoint> &keypoints;
1114 Mat &descriptors;
1115 int nOctaveLayers;
1116 int firstOctave;
1117};
1118
1119static void calcDescriptors(const std::vector<Mat> &gpyr,
1120 const std::vector<KeyPoint> &keypoints,
1121 Mat &descriptors, int nOctaveLayers,
1122 int firstOctave) {
1123 parallel_for_(Range(0, static_cast<int>(keypoints.size())),
1124 calcDescriptorsComputer(gpyr, keypoints, descriptors,
1125 nOctaveLayers, firstOctave));
1126}
1127
1128} // namespace
1129
1130//////////////////////////////////////////////////////////////////////////////////////////
1131
1132SIFT971_Impl::SIFT971_Impl(int _nfeatures, int _nOctaveLayers,
1133 double _contrastThreshold, double _edgeThreshold,
1134 double _sigma)
1135 : nfeatures(_nfeatures),
1136 nOctaveLayers(_nOctaveLayers),
1137 contrastThreshold(_contrastThreshold),
1138 edgeThreshold(_edgeThreshold),
1139 sigma(_sigma) {}
1140
1141int SIFT971_Impl::descriptorSize() const {
1142 return SIFT_DESCR_WIDTH * SIFT_DESCR_WIDTH * SIFT_DESCR_HIST_BINS;
1143}
1144
1145int SIFT971_Impl::descriptorType() const { return CV_32F; }
1146
1147int SIFT971_Impl::defaultNorm() const { return NORM_L2; }
1148
1149void SIFT971_Impl::detectAndCompute(InputArray _image, InputArray _mask,
1150 std::vector<KeyPoint> &keypoints,
1151 OutputArray _descriptors,
1152 bool useProvidedKeypoints) {
Brian Silverman3fec6482020-01-19 17:56:20 -08001153 int firstOctave = 0, actualNOctaves = 0, actualNLayers = 0;
Brian Silvermanf1196122020-01-16 00:41:54 -08001154 Mat image = _image.getMat(), mask = _mask.getMat();
1155
1156 if (image.empty() || image.depth() != CV_8U)
1157 CV_Error(Error::StsBadArg,
1158 "image is empty or has incorrect depth (!=CV_8U)");
1159
1160 if (!mask.empty() && mask.type() != CV_8UC1)
1161 CV_Error(Error::StsBadArg, "mask has incorrect type (!=CV_8UC1)");
1162
1163 if (useProvidedKeypoints) {
Brian Silverman3fec6482020-01-19 17:56:20 -08001164 LOG_IF(INFO, kLogTiming);
Brian Silvermanf1196122020-01-16 00:41:54 -08001165 firstOctave = 0;
1166 int maxOctave = INT_MIN;
1167 for (size_t i = 0; i < keypoints.size(); i++) {
1168 int octave, layer;
1169 float scale;
1170 unpackOctave(keypoints[i], octave, layer, scale);
1171 firstOctave = std::min(firstOctave, octave);
1172 maxOctave = std::max(maxOctave, octave);
1173 actualNLayers = std::max(actualNLayers, layer - 2);
1174 }
1175
1176 firstOctave = std::min(firstOctave, 0);
1177 CV_Assert(firstOctave >= -1 && actualNLayers <= nOctaveLayers);
1178 actualNOctaves = maxOctave - firstOctave + 1;
1179 }
1180
Brian Silverman3fec6482020-01-19 17:56:20 -08001181 LOG_IF(INFO, kLogTiming);
1182 Mat base = createInitialImage(image, firstOctave < 0);
1183 LOG_IF(INFO, kLogTiming);
Brian Silvermanf1196122020-01-16 00:41:54 -08001184 std::vector<Mat> gpyr;
Brian Silverman3fec6482020-01-19 17:56:20 -08001185 int nOctaves;
1186 if (actualNOctaves > 0) {
1187 nOctaves = actualNOctaves;
1188 } else {
1189 nOctaves = cvRound(std::log((double)std::min(base.cols, base.rows)) /
1190 std::log(2.) -
1191 2) -
1192 firstOctave;
1193 }
Brian Silvermanf1196122020-01-16 00:41:54 -08001194
1195 if (!useProvidedKeypoints) {
1196 std::vector<Mat> dogpyr;
Brian Silverman3fec6482020-01-19 17:56:20 -08001197 if (use_fused_pyramid_difference_) {
1198 buildGaussianAndDifferencePyramid(base, gpyr, dogpyr, nOctaves);
1199 LOG_IF(INFO, kLogTiming);
1200 } else {
1201 buildGaussianPyramid(base, gpyr, nOctaves);
1202 LOG_IF(INFO, kLogTiming);
1203
1204 buildDoGPyramid(gpyr, dogpyr);
1205 LOG_IF(INFO, kLogTiming);
1206 }
1207
Brian Silvermanf1196122020-01-16 00:41:54 -08001208 findScaleSpaceExtrema(gpyr, dogpyr, keypoints);
1209 // TODO(Brian): I think it can go faster by knowing they're sorted?
1210 // KeyPointsFilter::removeDuplicatedSorted( keypoints );
1211 KeyPointsFilter::removeDuplicated(keypoints);
1212
1213 if (nfeatures > 0) KeyPointsFilter::retainBest(keypoints, nfeatures);
Brian Silvermanf1196122020-01-16 00:41:54 -08001214
1215 if (firstOctave < 0)
1216 for (size_t i = 0; i < keypoints.size(); i++) {
1217 KeyPoint &kpt = keypoints[i];
1218 float scale = 1.f / (float)(1 << -firstOctave);
1219 kpt.octave = (kpt.octave & ~255) | ((kpt.octave + firstOctave) & 255);
1220 kpt.pt *= scale;
1221 kpt.size *= scale;
1222 }
1223
1224 if (!mask.empty()) KeyPointsFilter::runByPixelsMask(keypoints, mask);
Brian Silverman3fec6482020-01-19 17:56:20 -08001225 LOG_IF(INFO, kLogTiming);
Brian Silvermanf1196122020-01-16 00:41:54 -08001226 } else {
Brian Silverman3fec6482020-01-19 17:56:20 -08001227 buildGaussianPyramid(base, gpyr, nOctaves);
1228 LOG_IF(INFO, kLogTiming);
Brian Silvermanf1196122020-01-16 00:41:54 -08001229 // filter keypoints by mask
1230 // KeyPointsFilter::runByPixelsMask( keypoints, mask );
1231 }
1232
1233 if (_descriptors.needed()) {
Brian Silvermanf1196122020-01-16 00:41:54 -08001234 int dsize = descriptorSize();
1235 _descriptors.create((int)keypoints.size(), dsize, CV_32F);
1236 Mat descriptors = _descriptors.getMat();
1237
1238 calcDescriptors(gpyr, keypoints, descriptors, nOctaveLayers, firstOctave);
Brian Silverman3fec6482020-01-19 17:56:20 -08001239 LOG_IF(INFO, kLogTiming);
1240 }
1241}
1242
1243Mat SIFT971_Impl::createInitialImage(const Mat &img,
1244 bool doubleImageSize) const {
1245 Mat gray, gray_fpt;
1246 if (img.channels() == 3 || img.channels() == 4) {
1247 cvtColor(img, gray, COLOR_BGR2GRAY);
1248 gray.convertTo(gray_fpt, DataType<sift_wt>::type, SIFT_FIXPT_SCALE, 0);
1249 } else {
1250 img.convertTo(gray_fpt, DataType<sift_wt>::type, SIFT_FIXPT_SCALE, 0);
1251 }
1252
1253 float sig_diff;
1254
1255 Mat maybe_doubled;
1256 if (doubleImageSize) {
1257 sig_diff = std::sqrt(
1258 std::max(sigma * sigma - SIFT_INIT_SIGMA * SIFT_INIT_SIGMA * 4, 0.01));
1259 resize(gray_fpt, maybe_doubled, Size(gray_fpt.cols * 2, gray_fpt.rows * 2),
1260 0, 0, INTER_LINEAR);
1261 } else {
1262 sig_diff = std::sqrt(
1263 std::max(sigma * sigma - SIFT_INIT_SIGMA * SIFT_INIT_SIGMA, 0.01));
1264 maybe_doubled = gray_fpt;
1265 }
1266 if (use_fast_guassian_initial_) {
1267 Mat temp;
1268 FastGaussian(maybe_doubled, &temp, sig_diff);
1269 return temp;
1270 } else {
1271 GaussianBlur(maybe_doubled, maybe_doubled, Size(), sig_diff, sig_diff);
1272 return maybe_doubled;
Brian Silvermanf1196122020-01-16 00:41:54 -08001273 }
1274}
1275
1276} // namespace vision
1277} // namespace frc971