blob: 93d71e461abc8869a23c726f00b13a16f012ba49 [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
Brian Silverman97ba4b12020-02-15 23:36:36 -0800297 // Precompute Gaussian sigmas using the following formula:
298 // \sigma_{total}^2 = \sigma_{i}^2 + \sigma_{i-1}^2
299 // We need one for each of the layers in the pyramid we blur, which skips the
300 // first one because it's just the base image without any blurring.
301 std::vector<double> sig(gpyr_layers_per_octave - 1);
Brian Silverman3fec6482020-01-19 17:56:20 -0800302 double k = std::pow(2., 1. / layers_per_octave);
Brian Silverman97ba4b12020-02-15 23:36:36 -0800303 for (int i = 0; i < gpyr_layers_per_octave - 1; i++) {
304 double sig_prev = std::pow<double>(k, i) * sigma;
Brian Silverman3fec6482020-01-19 17:56:20 -0800305 double sig_total = sig_prev * k;
306 sig[i] = std::sqrt(sig_total * sig_total - sig_prev * sig_prev);
307 }
308
309 for (int octave = 0; octave < number_octaves; octave++) {
Brian Silverman97ba4b12020-02-15 23:36:36 -0800310 const int octave_gpyr_index = octave * gpyr_layers_per_octave;
311 const int octave_dogpyr_index = octave * dogpyr_layers_per_octave;
312
Brian Silverman3fec6482020-01-19 17:56:20 -0800313 // At the beginning of each octave, calculate the new base image.
314 {
Brian Silverman97ba4b12020-02-15 23:36:36 -0800315 Mat &dst = gpyr[octave_gpyr_index];
Brian Silverman3fec6482020-01-19 17:56:20 -0800316 if (octave == 0) {
317 // For the first octave, it's just the base image.
318 dst = base;
319 } else {
Brian Silverman97ba4b12020-02-15 23:36:36 -0800320 // For the other octaves, OpenCV's code claims that it's a halved
321 // version of the end of the previous octave.
322 // TODO(Brian): But this isn't really the end of the previous octave?
323 // But if you use the end, it finds way fewer features? Maybe this is
324 // just a arbitrarily-ish-somewhat-blurred thing from the previous
325 // octave??
326 const int gpyr_index = octave_gpyr_index - 3;
327 // Verify that the indexing in the original OpenCV code gives the same
328 // result. It's unclear which one makes more logical sense.
329 CHECK_EQ((octave - 1) * gpyr_layers_per_octave + layers_per_octave,
330 gpyr_index);
331 const Mat &src = gpyr[gpyr_index];
Brian Silverman3fec6482020-01-19 17:56:20 -0800332 resize(src, dst, Size(src.cols / 2, src.rows / 2), 0, 0, INTER_NEAREST);
333 }
334 }
Brian Silverman97ba4b12020-02-15 23:36:36 -0800335
336 // Then, go through all the layers and calculate the appropriate
337 // differences.
338 for (int layer = 0; layer < dogpyr_layers_per_octave; layer++) {
Brian Silverman3fec6482020-01-19 17:56:20 -0800339 // The index where the current layer starts.
Brian Silverman97ba4b12020-02-15 23:36:36 -0800340 const int layer_gpyr_index = octave_gpyr_index + layer;
341 const int layer_dogpyr_index = octave_dogpyr_index + layer;
342
Brian Silverman3fec6482020-01-19 17:56:20 -0800343 if (use_fast_pyramid_difference_) {
Brian Silverman97ba4b12020-02-15 23:36:36 -0800344 const Mat &input = gpyr[layer_gpyr_index];
345 Mat &blurred = gpyr[layer_gpyr_index + 1];
346 Mat &difference = dogpyr[layer_dogpyr_index];
Brian Silverman3fec6482020-01-19 17:56:20 -0800347 FastGaussianAndSubtract(input, &blurred, &difference, sig[layer]);
348 } else {
349 // First, calculate the new gaussian blur.
350 {
Brian Silverman97ba4b12020-02-15 23:36:36 -0800351 const Mat &src = gpyr[layer_gpyr_index];
352 Mat &dst = gpyr[layer_gpyr_index + 1];
Brian Silverman3fec6482020-01-19 17:56:20 -0800353 if (use_fast_gaussian_pyramid_) {
354 FastGaussian(src, &dst, sig[layer]);
355 } else {
356 GaussianBlur(src, dst, Size(), sig[layer], sig[layer]);
357 }
358 }
359
360 // Then, calculate the difference from the previous one.
361 {
Brian Silverman97ba4b12020-02-15 23:36:36 -0800362 const Mat &src1 = gpyr[layer_gpyr_index];
363 const Mat &src2 = gpyr[layer_gpyr_index + 1];
364 Mat &dst = dogpyr[layer_dogpyr_index];
Brian Silverman3fec6482020-01-19 17:56:20 -0800365 if (use_fast_subtract_dogpyr_) {
366 FastSubtract(src2, src1, &dst);
367 } else {
368 subtract(src2, src1, dst, noArray(), DataType<sift_wt>::type);
369 }
370 }
371 }
372 }
373 }
Brian Silvermanf1196122020-01-16 00:41:54 -0800374}
375
376namespace {
377
378// Computes a gradient orientation histogram at a specified pixel
379static float calcOrientationHist(const Mat &img, Point pt, int radius,
380 float sigma, float *hist, int n) {
381 int i, j, k, len = (radius * 2 + 1) * (radius * 2 + 1);
382
383 float expf_scale = -1.f / (2.f * sigma * sigma);
384 AutoBuffer<float> buf(len * 4 + n + 4);
385 float *X = buf, *Y = X + len, *Mag = X, *Ori = Y + len, *W = Ori + len;
386 float *temphist = W + len + 2;
387
388 for (i = 0; i < n; i++) temphist[i] = 0.f;
389
390 for (i = -radius, k = 0; i <= radius; i++) {
391 int y = pt.y + i;
392 if (y <= 0 || y >= img.rows - 1) continue;
393 for (j = -radius; j <= radius; j++) {
394 int x = pt.x + j;
395 if (x <= 0 || x >= img.cols - 1) continue;
396
397 float dx = (float)(img.at<sift_wt>(y, x + 1) - img.at<sift_wt>(y, x - 1));
398 float dy = (float)(img.at<sift_wt>(y - 1, x) - img.at<sift_wt>(y + 1, x));
399
400 X[k] = dx;
401 Y[k] = dy;
402 W[k] = (i * i + j * j) * expf_scale;
403 k++;
404 }
405 }
406
407 len = k;
408
409 // compute gradient values, orientations and the weights over the pixel
410 // neighborhood
411 cv::hal::exp32f(W, W, len);
412 cv::hal::fastAtan2(Y, X, Ori, len, true);
413 cv::hal::magnitude32f(X, Y, Mag, len);
414
415 k = 0;
416#if CV_AVX2
417 if (USE_AVX2) {
418 __m256 __nd360 = _mm256_set1_ps(n / 360.f);
419 __m256i __n = _mm256_set1_epi32(n);
420 int CV_DECL_ALIGNED(32) bin_buf[8];
421 float CV_DECL_ALIGNED(32) w_mul_mag_buf[8];
422 for (; k <= len - 8; k += 8) {
423 __m256i __bin =
424 _mm256_cvtps_epi32(_mm256_mul_ps(__nd360, _mm256_loadu_ps(&Ori[k])));
425
426 __bin = _mm256_sub_epi32(
427 __bin, _mm256_andnot_si256(_mm256_cmpgt_epi32(__n, __bin), __n));
428 __bin = _mm256_add_epi32(
429 __bin, _mm256_and_si256(
430 __n, _mm256_cmpgt_epi32(_mm256_setzero_si256(), __bin)));
431
432 __m256 __w_mul_mag =
433 _mm256_mul_ps(_mm256_loadu_ps(&W[k]), _mm256_loadu_ps(&Mag[k]));
434
435 _mm256_store_si256((__m256i *)bin_buf, __bin);
436 _mm256_store_ps(w_mul_mag_buf, __w_mul_mag);
437
438 temphist[bin_buf[0]] += w_mul_mag_buf[0];
439 temphist[bin_buf[1]] += w_mul_mag_buf[1];
440 temphist[bin_buf[2]] += w_mul_mag_buf[2];
441 temphist[bin_buf[3]] += w_mul_mag_buf[3];
442 temphist[bin_buf[4]] += w_mul_mag_buf[4];
443 temphist[bin_buf[5]] += w_mul_mag_buf[5];
444 temphist[bin_buf[6]] += w_mul_mag_buf[6];
445 temphist[bin_buf[7]] += w_mul_mag_buf[7];
446 }
447 }
448#endif
449 for (; k < len; k++) {
450 int bin = cvRound((n / 360.f) * Ori[k]);
451 if (bin >= n) bin -= n;
452 if (bin < 0) bin += n;
453 temphist[bin] += W[k] * Mag[k];
454 }
455
456 // smooth the histogram
457 temphist[-1] = temphist[n - 1];
458 temphist[-2] = temphist[n - 2];
459 temphist[n] = temphist[0];
460 temphist[n + 1] = temphist[1];
461
462 i = 0;
463#if CV_AVX2
464 if (USE_AVX2) {
465 __m256 __d_1_16 = _mm256_set1_ps(1.f / 16.f);
466 __m256 __d_4_16 = _mm256_set1_ps(4.f / 16.f);
467 __m256 __d_6_16 = _mm256_set1_ps(6.f / 16.f);
468 for (; i <= n - 8; i += 8) {
469#if CV_FMA3
470 __m256 __hist = _mm256_fmadd_ps(
471 _mm256_add_ps(_mm256_loadu_ps(&temphist[i - 2]),
472 _mm256_loadu_ps(&temphist[i + 2])),
473 __d_1_16,
474 _mm256_fmadd_ps(
475 _mm256_add_ps(_mm256_loadu_ps(&temphist[i - 1]),
476 _mm256_loadu_ps(&temphist[i + 1])),
477 __d_4_16,
478 _mm256_mul_ps(_mm256_loadu_ps(&temphist[i]), __d_6_16)));
479#else
480 __m256 __hist = _mm256_add_ps(
481 _mm256_mul_ps(_mm256_add_ps(_mm256_loadu_ps(&temphist[i - 2]),
482 _mm256_loadu_ps(&temphist[i + 2])),
483 __d_1_16),
484 _mm256_add_ps(
485 _mm256_mul_ps(_mm256_add_ps(_mm256_loadu_ps(&temphist[i - 1]),
486 _mm256_loadu_ps(&temphist[i + 1])),
487 __d_4_16),
488 _mm256_mul_ps(_mm256_loadu_ps(&temphist[i]), __d_6_16)));
489#endif
490 _mm256_storeu_ps(&hist[i], __hist);
491 }
492 }
493#endif
494 for (; i < n; i++) {
495 hist[i] = (temphist[i - 2] + temphist[i + 2]) * (1.f / 16.f) +
496 (temphist[i - 1] + temphist[i + 1]) * (4.f / 16.f) +
497 temphist[i] * (6.f / 16.f);
498 }
499
500 float maxval = hist[0];
501 for (i = 1; i < n; i++) maxval = std::max(maxval, hist[i]);
502
503 return maxval;
504}
505
506//
507// Interpolates a scale-space extremum's location and scale to subpixel
508// accuracy to form an image feature. Rejects features with low contrast.
509// Based on Section 4 of Lowe's paper.
510static bool adjustLocalExtrema(const std::vector<Mat> &dog_pyr, KeyPoint &kpt,
511 int octv, int &layer, int &r, int &c,
512 int nOctaveLayers, float contrastThreshold,
513 float edgeThreshold, float sigma) {
514 const float img_scale = 1.f / (255 * SIFT_FIXPT_SCALE);
515 const float deriv_scale = img_scale * 0.5f;
516 const float second_deriv_scale = img_scale;
517 const float cross_deriv_scale = img_scale * 0.25f;
518
519 float xi = 0, xr = 0, xc = 0, contr = 0;
520 int i = 0;
521
522 for (; i < SIFT_MAX_INTERP_STEPS; i++) {
523 int idx = octv * (nOctaveLayers + 2) + layer;
524 const Mat &img = dog_pyr[idx];
525 const Mat &prev = dog_pyr[idx - 1];
526 const Mat &next = dog_pyr[idx + 1];
527
528 Vec3f dD(
529 (img.at<sift_wt>(r, c + 1) - img.at<sift_wt>(r, c - 1)) * deriv_scale,
530 (img.at<sift_wt>(r + 1, c) - img.at<sift_wt>(r - 1, c)) * deriv_scale,
531 (next.at<sift_wt>(r, c) - prev.at<sift_wt>(r, c)) * deriv_scale);
532
533 float v2 = (float)img.at<sift_wt>(r, c) * 2;
534 float dxx = (img.at<sift_wt>(r, c + 1) + img.at<sift_wt>(r, c - 1) - v2) *
535 second_deriv_scale;
536 float dyy = (img.at<sift_wt>(r + 1, c) + img.at<sift_wt>(r - 1, c) - v2) *
537 second_deriv_scale;
538 float dss = (next.at<sift_wt>(r, c) + prev.at<sift_wt>(r, c) - v2) *
539 second_deriv_scale;
540 float dxy =
541 (img.at<sift_wt>(r + 1, c + 1) - img.at<sift_wt>(r + 1, c - 1) -
542 img.at<sift_wt>(r - 1, c + 1) + img.at<sift_wt>(r - 1, c - 1)) *
543 cross_deriv_scale;
544 float dxs = (next.at<sift_wt>(r, c + 1) - next.at<sift_wt>(r, c - 1) -
545 prev.at<sift_wt>(r, c + 1) + prev.at<sift_wt>(r, c - 1)) *
546 cross_deriv_scale;
547 float dys = (next.at<sift_wt>(r + 1, c) - next.at<sift_wt>(r - 1, c) -
548 prev.at<sift_wt>(r + 1, c) + prev.at<sift_wt>(r - 1, c)) *
549 cross_deriv_scale;
550
551 Matx33f H(dxx, dxy, dxs, dxy, dyy, dys, dxs, dys, dss);
552
553 Vec3f X = H.solve(dD, DECOMP_LU);
554
555 xi = -X[2];
556 xr = -X[1];
557 xc = -X[0];
558
559 if (std::abs(xi) < 0.5f && std::abs(xr) < 0.5f && std::abs(xc) < 0.5f)
560 break;
561
562 if (std::abs(xi) > (float)(INT_MAX / 3) ||
563 std::abs(xr) > (float)(INT_MAX / 3) ||
564 std::abs(xc) > (float)(INT_MAX / 3))
565 return false;
566
567 c += cvRound(xc);
568 r += cvRound(xr);
569 layer += cvRound(xi);
570
571 if (layer < 1 || layer > nOctaveLayers || c < SIFT_IMG_BORDER ||
572 c >= img.cols - SIFT_IMG_BORDER || r < SIFT_IMG_BORDER ||
573 r >= img.rows - SIFT_IMG_BORDER)
574 return false;
575 }
576
577 // ensure convergence of interpolation
578 if (i >= SIFT_MAX_INTERP_STEPS) return false;
579
580 {
581 int idx = octv * (nOctaveLayers + 2) + layer;
582 const Mat &img = dog_pyr[idx];
583 const Mat &prev = dog_pyr[idx - 1];
584 const Mat &next = dog_pyr[idx + 1];
585 Matx31f dD(
586 (img.at<sift_wt>(r, c + 1) - img.at<sift_wt>(r, c - 1)) * deriv_scale,
587 (img.at<sift_wt>(r + 1, c) - img.at<sift_wt>(r - 1, c)) * deriv_scale,
588 (next.at<sift_wt>(r, c) - prev.at<sift_wt>(r, c)) * deriv_scale);
589 float t = dD.dot(Matx31f(xc, xr, xi));
590
591 contr = img.at<sift_wt>(r, c) * img_scale + t * 0.5f;
592 if (std::abs(contr) * nOctaveLayers < contrastThreshold) return false;
593
594 // principal curvatures are computed using the trace and det of Hessian
595 float v2 = img.at<sift_wt>(r, c) * 2.f;
596 float dxx = (img.at<sift_wt>(r, c + 1) + img.at<sift_wt>(r, c - 1) - v2) *
597 second_deriv_scale;
598 float dyy = (img.at<sift_wt>(r + 1, c) + img.at<sift_wt>(r - 1, c) - v2) *
599 second_deriv_scale;
600 float dxy =
601 (img.at<sift_wt>(r + 1, c + 1) - img.at<sift_wt>(r + 1, c - 1) -
602 img.at<sift_wt>(r - 1, c + 1) + img.at<sift_wt>(r - 1, c - 1)) *
603 cross_deriv_scale;
604 float tr = dxx + dyy;
605 float det = dxx * dyy - dxy * dxy;
606
607 if (det <= 0 || tr * tr * edgeThreshold >=
608 (edgeThreshold + 1) * (edgeThreshold + 1) * det)
609 return false;
610 }
611
612 kpt.pt.x = (c + xc) * (1 << octv);
613 kpt.pt.y = (r + xr) * (1 << octv);
614 kpt.octave = octv + (layer << 8) + (cvRound((xi + 0.5) * 255) << 16);
615 kpt.size = sigma * powf(2.f, (layer + xi) / nOctaveLayers) * (1 << octv) * 2;
616 kpt.response = std::abs(contr);
617
618 return true;
619}
620
621template <typename T>
622class PerThreadAccumulator {
623 public:
624 void Add(std::vector<T> &&data) {
625 std::unique_lock locker(mutex_);
626 result_.emplace_back(data);
627 }
628
629 std::vector<std::vector<T>> move_result() { return std::move(result_); }
630
631 private:
632 // Should we do something more intelligent with per-thread std::vector that we
633 // merge at the end?
634 std::vector<std::vector<T>> result_;
635 std::mutex mutex_;
636};
637
638class findScaleSpaceExtremaComputer : public ParallelLoopBody {
639 public:
640 findScaleSpaceExtremaComputer(
641 int _o, int _i, int _threshold, int _idx, int _step, int _cols,
642 int _nOctaveLayers, double _contrastThreshold, double _edgeThreshold,
643 double _sigma, const std::vector<Mat> &_gauss_pyr,
644 const std::vector<Mat> &_dog_pyr,
645 PerThreadAccumulator<KeyPoint> &_tls_kpts_struct)
646
647 : o(_o),
648 i(_i),
649 threshold(_threshold),
650 idx(_idx),
651 step(_step),
652 cols(_cols),
653 nOctaveLayers(_nOctaveLayers),
654 contrastThreshold(_contrastThreshold),
655 edgeThreshold(_edgeThreshold),
656 sigma(_sigma),
657 gauss_pyr(_gauss_pyr),
658 dog_pyr(_dog_pyr),
659 tls_kpts_struct(_tls_kpts_struct) {}
660 void operator()(const cv::Range &range) const override {
661 const int begin = range.start;
662 const int end = range.end;
663
664 static const int n = SIFT_ORI_HIST_BINS;
665 float hist[n];
666
667 const Mat &img = dog_pyr[idx];
668 const Mat &prev = dog_pyr[idx - 1];
669 const Mat &next = dog_pyr[idx + 1];
670
671 std::vector<KeyPoint> tls_kpts;
672
673 KeyPoint kpt;
674 for (int r = begin; r < end; r++) {
675 const sift_wt *currptr = img.ptr<sift_wt>(r);
676 const sift_wt *prevptr = prev.ptr<sift_wt>(r);
677 const sift_wt *nextptr = next.ptr<sift_wt>(r);
678
679 for (int c = SIFT_IMG_BORDER; c < cols - SIFT_IMG_BORDER; c++) {
680 sift_wt val = currptr[c];
681
682 // find local extrema with pixel accuracy
683 if (std::abs(val) > threshold &&
684 ((val > 0 && val >= currptr[c - 1] && val >= currptr[c + 1] &&
685 val >= currptr[c - step - 1] && val >= currptr[c - step] &&
686 val >= currptr[c - step + 1] && val >= currptr[c + step - 1] &&
687 val >= currptr[c + step] && val >= currptr[c + step + 1] &&
688 val >= nextptr[c] && val >= nextptr[c - 1] &&
689 val >= nextptr[c + 1] && val >= nextptr[c - step - 1] &&
690 val >= nextptr[c - step] && val >= nextptr[c - step + 1] &&
691 val >= nextptr[c + step - 1] && val >= nextptr[c + step] &&
692 val >= nextptr[c + step + 1] && val >= prevptr[c] &&
693 val >= prevptr[c - 1] && val >= prevptr[c + 1] &&
694 val >= prevptr[c - step - 1] && val >= prevptr[c - step] &&
695 val >= prevptr[c - step + 1] && val >= prevptr[c + step - 1] &&
696 val >= prevptr[c + step] && val >= prevptr[c + step + 1]) ||
697 (val < 0 && val <= currptr[c - 1] && val <= currptr[c + 1] &&
698 val <= currptr[c - step - 1] && val <= currptr[c - step] &&
699 val <= currptr[c - step + 1] && val <= currptr[c + step - 1] &&
700 val <= currptr[c + step] && val <= currptr[c + step + 1] &&
701 val <= nextptr[c] && val <= nextptr[c - 1] &&
702 val <= nextptr[c + 1] && val <= nextptr[c - step - 1] &&
703 val <= nextptr[c - step] && val <= nextptr[c - step + 1] &&
704 val <= nextptr[c + step - 1] && val <= nextptr[c + step] &&
705 val <= nextptr[c + step + 1] && val <= prevptr[c] &&
706 val <= prevptr[c - 1] && val <= prevptr[c + 1] &&
707 val <= prevptr[c - step - 1] && val <= prevptr[c - step] &&
708 val <= prevptr[c - step + 1] && val <= prevptr[c + step - 1] &&
709 val <= prevptr[c + step] && val <= prevptr[c + step + 1]))) {
710 int r1 = r, c1 = c, layer = i;
711 if (!adjustLocalExtrema(dog_pyr, kpt, o, layer, r1, c1, nOctaveLayers,
712 (float)contrastThreshold,
713 (float)edgeThreshold, (float)sigma))
714 continue;
715 float scl_octv = kpt.size * 0.5f / (1 << o);
716 float omax = calcOrientationHist(
717 gauss_pyr[o * (nOctaveLayers + 3) + layer], Point(c1, r1),
718 cvRound(SIFT_ORI_RADIUS * scl_octv), SIFT_ORI_SIG_FCTR * scl_octv,
719 hist, n);
720 float mag_thr = (float)(omax * SIFT_ORI_PEAK_RATIO);
721 for (int j = 0; j < n; j++) {
722 int l = j > 0 ? j - 1 : n - 1;
723 int r2 = j < n - 1 ? j + 1 : 0;
724
725 if (hist[j] > hist[l] && hist[j] > hist[r2] && hist[j] >= mag_thr) {
726 float bin = j + 0.5f * (hist[l] - hist[r2]) /
727 (hist[l] - 2 * hist[j] + hist[r2]);
728 bin = bin < 0 ? n + bin : bin >= n ? bin - n : bin;
729 kpt.angle = 360.f - (float)((360.f / n) * bin);
730 if (std::abs(kpt.angle - 360.f) < FLT_EPSILON) kpt.angle = 0.f;
731 { tls_kpts.push_back(kpt); }
732 }
733 }
734 }
735 }
736 }
737
738 tls_kpts_struct.Add(std::move(tls_kpts));
739 }
740
741 private:
742 int o, i;
743 int threshold;
744 int idx, step, cols;
745 int nOctaveLayers;
746 double contrastThreshold;
747 double edgeThreshold;
748 double sigma;
749 const std::vector<Mat> &gauss_pyr;
750 const std::vector<Mat> &dog_pyr;
751 PerThreadAccumulator<KeyPoint> &tls_kpts_struct;
752};
753
754} // namespace
755
756//
757// Detects features at extrema in DoG scale space. Bad features are discarded
758// based on contrast and ratio of principal curvatures.
759void SIFT971_Impl::findScaleSpaceExtrema(
760 const std::vector<Mat> &gauss_pyr, const std::vector<Mat> &dog_pyr,
761 std::vector<KeyPoint> &keypoints) const {
762 const int nOctaves = (int)gauss_pyr.size() / (nOctaveLayers + 3);
763 const int threshold =
764 cvFloor(0.5 * contrastThreshold / nOctaveLayers * 255 * SIFT_FIXPT_SCALE);
765
766 keypoints.clear();
767 PerThreadAccumulator<KeyPoint> tls_kpts_struct;
768
769 for (int o = 0; o < nOctaves; o++)
770 for (int i = 1; i <= nOctaveLayers; i++) {
771 const int idx = o * (nOctaveLayers + 2) + i;
772 const Mat &img = dog_pyr[idx];
773 const int step = (int)img.step1();
774 const int rows = img.rows, cols = img.cols;
775
776 parallel_for_(Range(SIFT_IMG_BORDER, rows - SIFT_IMG_BORDER),
777 findScaleSpaceExtremaComputer(
778 o, i, threshold, idx, step, cols, nOctaveLayers,
779 contrastThreshold, edgeThreshold, sigma, gauss_pyr,
780 dog_pyr, tls_kpts_struct));
781 }
782
783 const std::vector<std::vector<KeyPoint>> kpt_vecs =
784 tls_kpts_struct.move_result();
785 for (size_t i = 0; i < kpt_vecs.size(); ++i) {
786 keypoints.insert(keypoints.end(), kpt_vecs[i].begin(), kpt_vecs[i].end());
787 }
788}
789
790namespace {
791
792static void calcSIFTDescriptor(const Mat &img, Point2f ptf, float ori,
793 float scl, int d, int n, float *dst) {
794 Point pt(cvRound(ptf.x), cvRound(ptf.y));
795 float cos_t = cosf(ori * (float)(CV_PI / 180));
796 float sin_t = sinf(ori * (float)(CV_PI / 180));
797 float bins_per_rad = n / 360.f;
798 float exp_scale = -1.f / (d * d * 0.5f);
799 float hist_width = SIFT_DESCR_SCL_FCTR * scl;
800 int radius = cvRound(hist_width * 1.4142135623730951f * (d + 1) * 0.5f);
801 // Clip the radius to the diagonal of the image to avoid autobuffer too large
802 // exception
803 radius = std::min(radius, (int)sqrt(((double)img.cols) * img.cols +
804 ((double)img.rows) * img.rows));
805 cos_t /= hist_width;
806 sin_t /= hist_width;
807
808 int i, j, k, len = (radius * 2 + 1) * (radius * 2 + 1),
809 histlen = (d + 2) * (d + 2) * (n + 2);
810 int rows = img.rows, cols = img.cols;
811
812 AutoBuffer<float> buf(len * 6 + histlen);
813 float *X = buf, *Y = X + len, *Mag = Y, *Ori = Mag + len, *W = Ori + len;
814 float *RBin = W + len, *CBin = RBin + len, *hist = CBin + len;
815
816 for (i = 0; i < d + 2; i++) {
817 for (j = 0; j < d + 2; j++)
818 for (k = 0; k < n + 2; k++) hist[(i * (d + 2) + j) * (n + 2) + k] = 0.;
819 }
820
821 for (i = -radius, k = 0; i <= radius; i++)
822 for (j = -radius; j <= radius; j++) {
823 // Calculate sample's histogram array coords rotated relative to ori.
824 // Subtract 0.5 so samples that fall e.g. in the center of row 1 (i.e.
825 // r_rot = 1.5) have full weight placed in row 1 after interpolation.
826 float c_rot = j * cos_t - i * sin_t;
827 float r_rot = j * sin_t + i * cos_t;
828 float rbin = r_rot + d / 2 - 0.5f;
829 float cbin = c_rot + d / 2 - 0.5f;
830 int r = pt.y + i, c = pt.x + j;
831
832 if (rbin > -1 && rbin < d && cbin > -1 && cbin < d && r > 0 &&
833 r < rows - 1 && c > 0 && c < cols - 1) {
834 float dx =
835 (float)(img.at<sift_wt>(r, c + 1) - img.at<sift_wt>(r, c - 1));
836 float dy =
837 (float)(img.at<sift_wt>(r - 1, c) - img.at<sift_wt>(r + 1, c));
838 X[k] = dx;
839 Y[k] = dy;
840 RBin[k] = rbin;
841 CBin[k] = cbin;
842 W[k] = (c_rot * c_rot + r_rot * r_rot) * exp_scale;
843 k++;
844 }
845 }
846
847 len = k;
848 cv::hal::fastAtan2(Y, X, Ori, len, true);
849 cv::hal::magnitude32f(X, Y, Mag, len);
850 cv::hal::exp32f(W, W, len);
851
852 k = 0;
853#if CV_AVX2
854 if (USE_AVX2) {
855 int CV_DECL_ALIGNED(32) idx_buf[8];
856 float CV_DECL_ALIGNED(32) rco_buf[64];
857 const __m256 __ori = _mm256_set1_ps(ori);
858 const __m256 __bins_per_rad = _mm256_set1_ps(bins_per_rad);
859 const __m256i __n = _mm256_set1_epi32(n);
860 for (; k <= len - 8; k += 8) {
861 __m256 __rbin = _mm256_loadu_ps(&RBin[k]);
862 __m256 __cbin = _mm256_loadu_ps(&CBin[k]);
863 __m256 __obin = _mm256_mul_ps(
864 _mm256_sub_ps(_mm256_loadu_ps(&Ori[k]), __ori), __bins_per_rad);
865 __m256 __mag =
866 _mm256_mul_ps(_mm256_loadu_ps(&Mag[k]), _mm256_loadu_ps(&W[k]));
867
868 __m256 __r0 = _mm256_floor_ps(__rbin);
869 __rbin = _mm256_sub_ps(__rbin, __r0);
870 __m256 __c0 = _mm256_floor_ps(__cbin);
871 __cbin = _mm256_sub_ps(__cbin, __c0);
872 __m256 __o0 = _mm256_floor_ps(__obin);
873 __obin = _mm256_sub_ps(__obin, __o0);
874
875 __m256i __o0i = _mm256_cvtps_epi32(__o0);
876 __o0i = _mm256_add_epi32(
877 __o0i, _mm256_and_si256(
878 __n, _mm256_cmpgt_epi32(_mm256_setzero_si256(), __o0i)));
879 __o0i = _mm256_sub_epi32(
880 __o0i, _mm256_andnot_si256(_mm256_cmpgt_epi32(__n, __o0i), __n));
881
882 __m256 __v_r1 = _mm256_mul_ps(__mag, __rbin);
883 __m256 __v_r0 = _mm256_sub_ps(__mag, __v_r1);
884
885 __m256 __v_rc11 = _mm256_mul_ps(__v_r1, __cbin);
886 __m256 __v_rc10 = _mm256_sub_ps(__v_r1, __v_rc11);
887
888 __m256 __v_rc01 = _mm256_mul_ps(__v_r0, __cbin);
889 __m256 __v_rc00 = _mm256_sub_ps(__v_r0, __v_rc01);
890
891 __m256 __v_rco111 = _mm256_mul_ps(__v_rc11, __obin);
892 __m256 __v_rco110 = _mm256_sub_ps(__v_rc11, __v_rco111);
893
894 __m256 __v_rco101 = _mm256_mul_ps(__v_rc10, __obin);
895 __m256 __v_rco100 = _mm256_sub_ps(__v_rc10, __v_rco101);
896
897 __m256 __v_rco011 = _mm256_mul_ps(__v_rc01, __obin);
898 __m256 __v_rco010 = _mm256_sub_ps(__v_rc01, __v_rco011);
899
900 __m256 __v_rco001 = _mm256_mul_ps(__v_rc00, __obin);
901 __m256 __v_rco000 = _mm256_sub_ps(__v_rc00, __v_rco001);
902
903 __m256i __one = _mm256_set1_epi32(1);
904 __m256i __idx = _mm256_add_epi32(
905 _mm256_mullo_epi32(
906 _mm256_add_epi32(
907 _mm256_mullo_epi32(
908 _mm256_add_epi32(_mm256_cvtps_epi32(__r0), __one),
909 _mm256_set1_epi32(d + 2)),
910 _mm256_add_epi32(_mm256_cvtps_epi32(__c0), __one)),
911 _mm256_set1_epi32(n + 2)),
912 __o0i);
913
914 _mm256_store_si256((__m256i *)idx_buf, __idx);
915
916 _mm256_store_ps(&(rco_buf[0]), __v_rco000);
917 _mm256_store_ps(&(rco_buf[8]), __v_rco001);
918 _mm256_store_ps(&(rco_buf[16]), __v_rco010);
919 _mm256_store_ps(&(rco_buf[24]), __v_rco011);
920 _mm256_store_ps(&(rco_buf[32]), __v_rco100);
921 _mm256_store_ps(&(rco_buf[40]), __v_rco101);
922 _mm256_store_ps(&(rco_buf[48]), __v_rco110);
923 _mm256_store_ps(&(rco_buf[56]), __v_rco111);
924#define HIST_SUM_HELPER(id) \
925 hist[idx_buf[(id)]] += rco_buf[(id)]; \
926 hist[idx_buf[(id)] + 1] += rco_buf[8 + (id)]; \
927 hist[idx_buf[(id)] + (n + 2)] += rco_buf[16 + (id)]; \
928 hist[idx_buf[(id)] + (n + 3)] += rco_buf[24 + (id)]; \
929 hist[idx_buf[(id)] + (d + 2) * (n + 2)] += rco_buf[32 + (id)]; \
930 hist[idx_buf[(id)] + (d + 2) * (n + 2) + 1] += rco_buf[40 + (id)]; \
931 hist[idx_buf[(id)] + (d + 3) * (n + 2)] += rco_buf[48 + (id)]; \
932 hist[idx_buf[(id)] + (d + 3) * (n + 2) + 1] += rco_buf[56 + (id)];
933
934 HIST_SUM_HELPER(0);
935 HIST_SUM_HELPER(1);
936 HIST_SUM_HELPER(2);
937 HIST_SUM_HELPER(3);
938 HIST_SUM_HELPER(4);
939 HIST_SUM_HELPER(5);
940 HIST_SUM_HELPER(6);
941 HIST_SUM_HELPER(7);
942
943#undef HIST_SUM_HELPER
944 }
945 }
946#endif
947 for (; k < len; k++) {
948 float rbin = RBin[k], cbin = CBin[k];
949 float obin = (Ori[k] - ori) * bins_per_rad;
950 float mag = Mag[k] * W[k];
951
952 int r0 = cvFloor(rbin);
953 int c0 = cvFloor(cbin);
954 int o0 = cvFloor(obin);
955 rbin -= r0;
956 cbin -= c0;
957 obin -= o0;
958
959 if (o0 < 0) o0 += n;
960 if (o0 >= n) o0 -= n;
961
962 // histogram update using tri-linear interpolation
963 float v_r1 = mag * rbin, v_r0 = mag - v_r1;
964 float v_rc11 = v_r1 * cbin, v_rc10 = v_r1 - v_rc11;
965 float v_rc01 = v_r0 * cbin, v_rc00 = v_r0 - v_rc01;
966 float v_rco111 = v_rc11 * obin, v_rco110 = v_rc11 - v_rco111;
967 float v_rco101 = v_rc10 * obin, v_rco100 = v_rc10 - v_rco101;
968 float v_rco011 = v_rc01 * obin, v_rco010 = v_rc01 - v_rco011;
969 float v_rco001 = v_rc00 * obin, v_rco000 = v_rc00 - v_rco001;
970
971 int idx = ((r0 + 1) * (d + 2) + c0 + 1) * (n + 2) + o0;
972 hist[idx] += v_rco000;
973 hist[idx + 1] += v_rco001;
974 hist[idx + (n + 2)] += v_rco010;
975 hist[idx + (n + 3)] += v_rco011;
976 hist[idx + (d + 2) * (n + 2)] += v_rco100;
977 hist[idx + (d + 2) * (n + 2) + 1] += v_rco101;
978 hist[idx + (d + 3) * (n + 2)] += v_rco110;
979 hist[idx + (d + 3) * (n + 2) + 1] += v_rco111;
980 }
981
982 // finalize histogram, since the orientation histograms are circular
983 for (i = 0; i < d; i++)
984 for (j = 0; j < d; j++) {
985 int idx = ((i + 1) * (d + 2) + (j + 1)) * (n + 2);
986 hist[idx] += hist[idx + n];
987 hist[idx + 1] += hist[idx + n + 1];
988 for (k = 0; k < n; k++) dst[(i * d + j) * n + k] = hist[idx + k];
989 }
990 // copy histogram to the descriptor,
991 // apply hysteresis thresholding
992 // and scale the result, so that it can be easily converted
993 // to byte array
994 float nrm2 = 0;
995 len = d * d * n;
996 k = 0;
997#if CV_AVX2
998 if (USE_AVX2) {
999 float CV_DECL_ALIGNED(32) nrm2_buf[8];
1000 __m256 __nrm2 = _mm256_setzero_ps();
1001 __m256 __dst;
1002 for (; k <= len - 8; k += 8) {
1003 __dst = _mm256_loadu_ps(&dst[k]);
1004#if CV_FMA3
1005 __nrm2 = _mm256_fmadd_ps(__dst, __dst, __nrm2);
1006#else
1007 __nrm2 = _mm256_add_ps(__nrm2, _mm256_mul_ps(__dst, __dst));
1008#endif
1009 }
1010 _mm256_store_ps(nrm2_buf, __nrm2);
1011 nrm2 = nrm2_buf[0] + nrm2_buf[1] + nrm2_buf[2] + nrm2_buf[3] + nrm2_buf[4] +
1012 nrm2_buf[5] + nrm2_buf[6] + nrm2_buf[7];
1013 }
1014#endif
1015 for (; k < len; k++) nrm2 += dst[k] * dst[k];
1016
1017 float thr = std::sqrt(nrm2) * SIFT_DESCR_MAG_THR;
1018
1019 i = 0, nrm2 = 0;
1020#if 0 // CV_AVX2
1021 // This code cannot be enabled because it sums nrm2 in a different order,
1022 // thus producing slightly different results
1023 if( USE_AVX2 )
1024 {
1025 float CV_DECL_ALIGNED(32) nrm2_buf[8];
1026 __m256 __dst;
1027 __m256 __nrm2 = _mm256_setzero_ps();
1028 __m256 __thr = _mm256_set1_ps(thr);
1029 for( ; i <= len - 8; i += 8 )
1030 {
1031 __dst = _mm256_loadu_ps(&dst[i]);
1032 __dst = _mm256_min_ps(__dst, __thr);
1033 _mm256_storeu_ps(&dst[i], __dst);
1034#if CV_FMA3
1035 __nrm2 = _mm256_fmadd_ps(__dst, __dst, __nrm2);
1036#else
1037 __nrm2 = _mm256_add_ps(__nrm2, _mm256_mul_ps(__dst, __dst));
1038#endif
1039 }
1040 _mm256_store_ps(nrm2_buf, __nrm2);
1041 nrm2 = nrm2_buf[0] + nrm2_buf[1] + nrm2_buf[2] + nrm2_buf[3] +
1042 nrm2_buf[4] + nrm2_buf[5] + nrm2_buf[6] + nrm2_buf[7];
1043 }
1044#endif
1045 for (; i < len; i++) {
1046 float val = std::min(dst[i], thr);
1047 dst[i] = val;
1048 nrm2 += val * val;
1049 }
1050 nrm2 = SIFT_INT_DESCR_FCTR / std::max(std::sqrt(nrm2), FLT_EPSILON);
1051
1052#if 1
1053 k = 0;
1054#if CV_AVX2
1055 if (USE_AVX2) {
1056 __m256 __dst;
1057 __m256 __min = _mm256_setzero_ps();
1058 __m256 __max = _mm256_set1_ps(255.0f); // max of uchar
1059 __m256 __nrm2 = _mm256_set1_ps(nrm2);
1060 for (k = 0; k <= len - 8; k += 8) {
1061 __dst = _mm256_loadu_ps(&dst[k]);
1062 __dst = _mm256_min_ps(
1063 _mm256_max_ps(
1064 _mm256_round_ps(_mm256_mul_ps(__dst, __nrm2),
1065 _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC),
1066 __min),
1067 __max);
1068 _mm256_storeu_ps(&dst[k], __dst);
1069 }
1070 }
1071#endif
1072 for (; k < len; k++) {
1073 dst[k] = saturate_cast<uchar>(dst[k] * nrm2);
1074 }
1075#else
1076 float nrm1 = 0;
1077 for (k = 0; k < len; k++) {
1078 dst[k] *= nrm2;
1079 nrm1 += dst[k];
1080 }
1081 nrm1 = 1.f / std::max(nrm1, FLT_EPSILON);
1082 for (k = 0; k < len; k++) {
1083 dst[k] = std::sqrt(dst[k] * nrm1); // saturate_cast<uchar>(std::sqrt(dst[k]
1084 // * nrm1)*SIFT_INT_DESCR_FCTR);
1085 }
1086#endif
1087}
1088
1089class calcDescriptorsComputer : public ParallelLoopBody {
1090 public:
1091 calcDescriptorsComputer(const std::vector<Mat> &_gpyr,
1092 const std::vector<KeyPoint> &_keypoints,
1093 Mat &_descriptors, int _nOctaveLayers,
1094 int _firstOctave)
1095 : gpyr(_gpyr),
1096 keypoints(_keypoints),
1097 descriptors(_descriptors),
1098 nOctaveLayers(_nOctaveLayers),
1099 firstOctave(_firstOctave) {}
1100
1101 void operator()(const cv::Range &range) const override {
1102 const int begin = range.start;
1103 const int end = range.end;
1104
1105 static const int d = SIFT_DESCR_WIDTH, n = SIFT_DESCR_HIST_BINS;
1106
1107 for (int i = begin; i < end; i++) {
1108 KeyPoint kpt = keypoints[i];
1109 int octave, layer;
1110 float scale;
1111 unpackOctave(kpt, octave, layer, scale);
1112 CV_Assert(octave >= firstOctave && layer <= nOctaveLayers + 2);
1113 float size = kpt.size * scale;
1114 Point2f ptf(kpt.pt.x * scale, kpt.pt.y * scale);
1115 const Mat &img =
1116 gpyr[(octave - firstOctave) * (nOctaveLayers + 3) + layer];
1117
1118 float angle = 360.f - kpt.angle;
1119 if (std::abs(angle - 360.f) < FLT_EPSILON) angle = 0.f;
1120 calcSIFTDescriptor(img, ptf, angle, size * 0.5f, d, n,
1121 descriptors.ptr<float>((int)i));
1122 }
1123 }
1124
1125 private:
1126 const std::vector<Mat> &gpyr;
1127 const std::vector<KeyPoint> &keypoints;
1128 Mat &descriptors;
1129 int nOctaveLayers;
1130 int firstOctave;
1131};
1132
1133static void calcDescriptors(const std::vector<Mat> &gpyr,
1134 const std::vector<KeyPoint> &keypoints,
1135 Mat &descriptors, int nOctaveLayers,
1136 int firstOctave) {
1137 parallel_for_(Range(0, static_cast<int>(keypoints.size())),
1138 calcDescriptorsComputer(gpyr, keypoints, descriptors,
1139 nOctaveLayers, firstOctave));
1140}
1141
1142} // namespace
1143
1144//////////////////////////////////////////////////////////////////////////////////////////
1145
1146SIFT971_Impl::SIFT971_Impl(int _nfeatures, int _nOctaveLayers,
1147 double _contrastThreshold, double _edgeThreshold,
1148 double _sigma)
1149 : nfeatures(_nfeatures),
1150 nOctaveLayers(_nOctaveLayers),
1151 contrastThreshold(_contrastThreshold),
1152 edgeThreshold(_edgeThreshold),
1153 sigma(_sigma) {}
1154
1155int SIFT971_Impl::descriptorSize() const {
1156 return SIFT_DESCR_WIDTH * SIFT_DESCR_WIDTH * SIFT_DESCR_HIST_BINS;
1157}
1158
1159int SIFT971_Impl::descriptorType() const { return CV_32F; }
1160
1161int SIFT971_Impl::defaultNorm() const { return NORM_L2; }
1162
1163void SIFT971_Impl::detectAndCompute(InputArray _image, InputArray _mask,
1164 std::vector<KeyPoint> &keypoints,
1165 OutputArray _descriptors,
1166 bool useProvidedKeypoints) {
Brian Silverman950bffa2020-02-01 16:53:49 -08001167 int firstOctave = -1, actualNOctaves = 0, actualNLayers = 0;
Brian Silvermanf1196122020-01-16 00:41:54 -08001168 Mat image = _image.getMat(), mask = _mask.getMat();
1169
1170 if (image.empty() || image.depth() != CV_8U)
1171 CV_Error(Error::StsBadArg,
1172 "image is empty or has incorrect depth (!=CV_8U)");
1173
1174 if (!mask.empty() && mask.type() != CV_8UC1)
1175 CV_Error(Error::StsBadArg, "mask has incorrect type (!=CV_8UC1)");
1176
1177 if (useProvidedKeypoints) {
Brian Silverman3fec6482020-01-19 17:56:20 -08001178 LOG_IF(INFO, kLogTiming);
Brian Silvermanf1196122020-01-16 00:41:54 -08001179 firstOctave = 0;
1180 int maxOctave = INT_MIN;
1181 for (size_t i = 0; i < keypoints.size(); i++) {
1182 int octave, layer;
1183 float scale;
1184 unpackOctave(keypoints[i], octave, layer, scale);
1185 firstOctave = std::min(firstOctave, octave);
1186 maxOctave = std::max(maxOctave, octave);
1187 actualNLayers = std::max(actualNLayers, layer - 2);
1188 }
1189
1190 firstOctave = std::min(firstOctave, 0);
1191 CV_Assert(firstOctave >= -1 && actualNLayers <= nOctaveLayers);
1192 actualNOctaves = maxOctave - firstOctave + 1;
1193 }
1194
Brian Silverman3fec6482020-01-19 17:56:20 -08001195 LOG_IF(INFO, kLogTiming);
1196 Mat base = createInitialImage(image, firstOctave < 0);
1197 LOG_IF(INFO, kLogTiming);
Brian Silvermanf1196122020-01-16 00:41:54 -08001198 std::vector<Mat> gpyr;
Brian Silverman3fec6482020-01-19 17:56:20 -08001199 int nOctaves;
1200 if (actualNOctaves > 0) {
1201 nOctaves = actualNOctaves;
1202 } else {
1203 nOctaves = cvRound(std::log((double)std::min(base.cols, base.rows)) /
1204 std::log(2.) -
1205 2) -
1206 firstOctave;
1207 }
Brian Silvermanf1196122020-01-16 00:41:54 -08001208
1209 if (!useProvidedKeypoints) {
1210 std::vector<Mat> dogpyr;
Brian Silverman3fec6482020-01-19 17:56:20 -08001211 if (use_fused_pyramid_difference_) {
1212 buildGaussianAndDifferencePyramid(base, gpyr, dogpyr, nOctaves);
1213 LOG_IF(INFO, kLogTiming);
1214 } else {
1215 buildGaussianPyramid(base, gpyr, nOctaves);
1216 LOG_IF(INFO, kLogTiming);
1217
1218 buildDoGPyramid(gpyr, dogpyr);
1219 LOG_IF(INFO, kLogTiming);
1220 }
1221
Brian Silvermanf1196122020-01-16 00:41:54 -08001222 findScaleSpaceExtrema(gpyr, dogpyr, keypoints);
1223 // TODO(Brian): I think it can go faster by knowing they're sorted?
1224 // KeyPointsFilter::removeDuplicatedSorted( keypoints );
1225 KeyPointsFilter::removeDuplicated(keypoints);
1226
1227 if (nfeatures > 0) KeyPointsFilter::retainBest(keypoints, nfeatures);
Brian Silvermanf1196122020-01-16 00:41:54 -08001228
1229 if (firstOctave < 0)
1230 for (size_t i = 0; i < keypoints.size(); i++) {
1231 KeyPoint &kpt = keypoints[i];
1232 float scale = 1.f / (float)(1 << -firstOctave);
1233 kpt.octave = (kpt.octave & ~255) | ((kpt.octave + firstOctave) & 255);
1234 kpt.pt *= scale;
1235 kpt.size *= scale;
1236 }
1237
1238 if (!mask.empty()) KeyPointsFilter::runByPixelsMask(keypoints, mask);
Brian Silverman3fec6482020-01-19 17:56:20 -08001239 LOG_IF(INFO, kLogTiming);
Brian Silvermanf1196122020-01-16 00:41:54 -08001240 } else {
Brian Silverman3fec6482020-01-19 17:56:20 -08001241 buildGaussianPyramid(base, gpyr, nOctaves);
1242 LOG_IF(INFO, kLogTiming);
Brian Silvermanf1196122020-01-16 00:41:54 -08001243 // filter keypoints by mask
1244 // KeyPointsFilter::runByPixelsMask( keypoints, mask );
1245 }
1246
1247 if (_descriptors.needed()) {
Brian Silvermanf1196122020-01-16 00:41:54 -08001248 int dsize = descriptorSize();
1249 _descriptors.create((int)keypoints.size(), dsize, CV_32F);
1250 Mat descriptors = _descriptors.getMat();
1251
1252 calcDescriptors(gpyr, keypoints, descriptors, nOctaveLayers, firstOctave);
Brian Silverman3fec6482020-01-19 17:56:20 -08001253 LOG_IF(INFO, kLogTiming);
1254 }
1255}
1256
1257Mat SIFT971_Impl::createInitialImage(const Mat &img,
1258 bool doubleImageSize) const {
1259 Mat gray, gray_fpt;
1260 if (img.channels() == 3 || img.channels() == 4) {
1261 cvtColor(img, gray, COLOR_BGR2GRAY);
1262 gray.convertTo(gray_fpt, DataType<sift_wt>::type, SIFT_FIXPT_SCALE, 0);
1263 } else {
1264 img.convertTo(gray_fpt, DataType<sift_wt>::type, SIFT_FIXPT_SCALE, 0);
1265 }
1266
1267 float sig_diff;
1268
1269 Mat maybe_doubled;
1270 if (doubleImageSize) {
1271 sig_diff = std::sqrt(
1272 std::max(sigma * sigma - SIFT_INIT_SIGMA * SIFT_INIT_SIGMA * 4, 0.01));
1273 resize(gray_fpt, maybe_doubled, Size(gray_fpt.cols * 2, gray_fpt.rows * 2),
1274 0, 0, INTER_LINEAR);
1275 } else {
1276 sig_diff = std::sqrt(
1277 std::max(sigma * sigma - SIFT_INIT_SIGMA * SIFT_INIT_SIGMA, 0.01));
1278 maybe_doubled = gray_fpt;
1279 }
1280 if (use_fast_guassian_initial_) {
1281 Mat temp;
1282 FastGaussian(maybe_doubled, &temp, sig_diff);
1283 return temp;
1284 } else {
1285 GaussianBlur(maybe_doubled, maybe_doubled, Size(), sig_diff, sig_diff);
1286 return maybe_doubled;
Brian Silvermanf1196122020-01-16 00:41:54 -08001287 }
1288}
1289
1290} // namespace vision
1291} // namespace frc971