Ocean
Loading...
Searching...
No Matches
NonMaximumSuppression.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8#ifndef META_OCEAN_CV_NON_MAXIMUM_SUPPRESSION_H
9#define META_OCEAN_CV_NON_MAXIMUM_SUPPRESSION_H
10
11#include "ocean/cv/CV.h"
13
14#include "ocean/base/Callback.h"
16#include "ocean/base/Worker.h"
17
18namespace Ocean
19{
20
21namespace CV
22{
23
24/**
25 * This class implements the possibility to find local maximum in a 2D array by applying a non-maximum-suppression search.
26 * The search is done within a 3x3 neighborhood (centered around the point of interest).<br>
27 * Use this class to determine e.g. reliable feature points.<br>
28 * The class supports bin accuracy (pixel accuracy) and sub-bin accuracy (sub-pixel accuracy).
29 *
30 * The non-maximum-suppression search is implemented by a vertical list holding maps of horizontal array elements.<br>
31 * The performance depends on the number of elements inserted into the individual maps.<br>
32 * Thus, do not add data elements with negligible value.
33 *
34 * It should be mentioned that the application of this class should be restricted to situations in which the entire filter response values do not exist already.<br>
35 * The performance boost comes with a simultaneous determination of filter responses and the insertion of possible candidates for maximum locations.
36 * @tparam T The data type of the individual elements that are applied for the non-maximum-suppression search.
37 * @ingroup cv
38 */
39template <typename T>
41{
42 public:
43
44 /**
45 * This class extends a 2D position by a third parameter storing a strength value.
46 * @tparam TCoordinate The data type of a scalar coordinate
47 * @tparam TStrength The data type of the strength parameter
48 */
49 template <typename TCoordinate, typename TStrength>
50 class StrengthPosition : public VectorT2<TCoordinate>
51 {
52 public:
53
54 /**
55 * Creates a new object with default strength parameter.
56 */
57 StrengthPosition() = default;
58
59 /**
60 * Creates a new object with explicit position and strength parameter.
61 * @param x Horizontal position
62 * @param y Vertical position
63 * @param strength The strength parameter
64 */
65 inline StrengthPosition(const TCoordinate x, const TCoordinate y, const TStrength& strength);
66
67 /**
68 * Returns the strength parameter of this object.
69 * @return Strength parameter
70 */
71 inline const TStrength& strength() const;
72
73 /**
74 * Compares the strength value of two objects.
75 * @param left The left object to compare
76 * @param right The right object to compare
77 * @return True, if so
78 * @tparam tLeftLargerThanRight True, to return whether left's strength is larger than right's strength; False, to return whether right is larger than left
79 */
80 template <bool tLeftLargerThanRight = true>
82
83 private:
84
85 /// Strength parameter of this object.
86 TStrength strength_ = TStrength();
87 };
88
89 /**
90 * Definition of a vector holding strength pixel positions.
91 */
92 template <typename TCoordinate, typename TStrength>
93 using StrengthPositions = std::vector<StrengthPosition<TCoordinate, TStrength>>;
94
95 /**
96 * Definition of a callback function used to determine the precise sub-pixel position of a specific point.
97 * The first parameter provides the horizontal position.<br>
98 * The second parameter provides the vertical position.<br>
99 * The third parameter provides the strength value.<br>
100 * The fourth parameter receives the precise horizontal position.<br>
101 * The fifth parameter receives the precise vertical position.<br>
102 * The sixth parameter receives the precise strength value.<br>
103 * The return parameter should be True if the precise position could be determined
104 */
105 template <typename TCoordinate, typename TStrength>
107
108 private:
109
110 /**
111 * This class holds the horizontal position and strength parameter of an interest pixel.
112 */
114 {
115 public:
116
117 /**
118 * Creates a new candidate object.
119 */
120 inline StrengthCandidate();
121
122 /**
123 * Creates a new candidate object with horizontal position and strength parameter.
124 * @param x Horizontal position in pixel
125 * @param strength The strength parameter
126 */
127 inline StrengthCandidate(const unsigned int x, const T& strength);
128
129 /**
130 * Returns the horizontal position of this candidate object.
131 * @return Horizontal position in pixel
132 */
133 inline unsigned int x() const;
134
135 /**
136 * Returns the strength parameter of this object.
137 * @return Strength parameter
138 */
139 inline const T& strength() const;
140
141 private:
142
143 /// Horizontal position of this object.
144 unsigned int positionX_ = (unsigned int)(-1);
145
146 /// Strength parameter of this object.
147 T strength_ = T();
148 };
149
150 /**
151 * Definition of a vector holding strength candidate objects.
152 */
153 using StrengthCandidateRow = std::vector<StrengthCandidate>;
154
155 /**
156 * Definition of a vector holding a vector of strength candidates.
157 */
159
160 public:
161
162 /**
163 * Move constructor.
164 * @param nonMaximumSuppression The object to be moved
165 */
166 NonMaximumSuppression(NonMaximumSuppression<T>&& nonMaximumSuppression) noexcept;
167
168 /**
169 * Copy constructor.
170 * @param nonMaximumSuppression The object to be moved
171 */
172 NonMaximumSuppression(const NonMaximumSuppression<T>& nonMaximumSuppression) noexcept;
173
174 /**
175 * Creates a new maximum suppression object with a predefined size.
176 * @param width The width of this object in pixel, with range [3, infinity)
177 * @param height The height of this object in pixel, with range [3, infinity)
178 * @param yOffset Optional offset in the vertical direction moving the suppression region by the specified number of rows, with range [0, infinity)
179 */
180 NonMaximumSuppression(const unsigned int width, const unsigned int height, const unsigned int yOffset = 0u) noexcept;
181
182 /**
183 * Returns the width of this object.
184 * @return Width in pixel
185 */
186 inline unsigned int width() const;
187
188 /**
189 * Returns the height of this object.
190 * @return Height in pixel
191 */
192 inline unsigned int height() const;
193
194 /**
195 * Returns the optional offset in the vertical direction.
196 * @return Optional vertical direction offset, 0 by default
197 */
198 inline unsigned int yOffset() const;
199
200 /**
201 * Adds a new candidate to this object.
202 * Beware: Due to performance issues do no add candidates with negligible strength parameter.
203 * @param x Horizontal position in pixel, with range [0, width() - 1]
204 * @param y Vertical position in pixel, with range [yOffset(), yOffset() + height() - 1]
205 * @param strength The strength parameter
206 * @see addCandidates(), removeCandidatesFromRight().
207 */
208 inline void addCandidate(const unsigned int x, const unsigned int y, const T& strength);
209
210 /**
211 * Adds new candidates to this object from a given buffer providing one value for each bin/pixel of this object.
212 * Beware: Due to performance reasons, you should use the addCandidate() function to add one single new candidate in the moment the filter response is larger than a specific threshold.<br>
213 * @param values The from which candidates will be added, must be width() * height() elements
214 * @param valuesPaddingElements The number of padding elements at the end of each values row, in elements, with range [0, infinity)
215 * @param firstColumn First column to be handled, with range [0, width() - 1]
216 * @param numberColumns Number of columns to be handled, with range [1, width() - firstColumn]
217 * @param firstRow First row to be handled, with range [yOffset(), height() - 1]
218 * @param numberRows Number of rows to be handled, with range [1, height() - firstRow]
219 * @param minimalThreshold The minimal threshold so that a value counts as candidate
220 * @param worker Optional worker object to distribute the computation
221 * @see addCandidate(), removeCandidatesFromRight().
222 */
223 void addCandidates(const T* values, const unsigned int valuesPaddingElements, const unsigned int firstColumn, const unsigned int numberColumns, const unsigned int firstRow, const unsigned int numberRows, const T& minimalThreshold, Worker* worker);
224
225 /**
226 * Removes all candidates from a specified row having a horizontal location equal or larger than a specified coordinate.
227 * @param x The horizontal coordinate specifying which candidates will be removed, all candidates with horizontal location >= x will be removed, with range [0, infinity)
228 * @param y The index of the row in which the candidates will be removed, with range [yOffset(), yOffset() + height() - 1]
229 */
230 inline void removeCandidatesRightFrom(const unsigned int x, const unsigned int y);
231
232 /**
233 * Applies a non-maximum-suppression search on a given 2D frame in a 3x3 neighborhood (eight neighbors).
234 * This function allows to determine the precise position of the individual maximum value positions by application of a callback function determining the individual positions.<br>
235 * @param firstColumn First column to be handled, with range [1, width() - 1)
236 * @param numberColumns Number of columns to be handled
237 * @param firstRow First row to be handled, with range [yOffset() + 1, height() - 1)
238 * @param numberRows Number of rows to be handled
239 * @param worker Optional worker object to distribute the computation
240 * @param positionCallback Optional callback function allowing to determine the precise position of the individual maximum value positions
241 * @return Resulting non maximum suppressed positions including the strength parameters
242 * @tparam TCoordinate The data type of a scalar coordinate
243 * @tparam TStrength The data type of the strength parameter
244 * @tparam tStrictMaximum True, to search for a strict maximum (larger than all eight neighbors); False, to allow equal values in the upper left neighborhood
245 */
246 template <typename TCoordinate, typename TStrength, bool tStrictMaximum = true>
247 StrengthPositions<TCoordinate, TStrength> suppressNonMaximum(const unsigned int firstColumn, const unsigned int numberColumns, const unsigned int firstRow, const unsigned int numberRows, Worker* worker = nullptr, const PositionCallback<TCoordinate, TStrength>* positionCallback = nullptr) const;
248
249 /**
250 * Returns all gathered candidates of this object.
251 * The resulting candidates are raw candidates without any suppression.
252 * @param firstColumn The first column from which candidates will be returned, with range [0, width() - 1]
253 * @param numberColumns The number of columns for which candidates will be returned, with range [1, width() - firstColumn]
254 * @param firstRow The first row from which candidates will be returned, with range [yOffset(), height() - 1]
255 * @param numberRows The number of rows for which candidates will be returned, with range [1, height() - firstRow]
256 * @param strengthPositions The resulting strength positions
257 */
258 void candidates(const unsigned int firstColumn, const unsigned int numberColumns, const unsigned int firstRow, const unsigned int numberRows, StrengthPositions<unsigned int, T>& strengthPositions);
259
260 /**
261 * Removes the gathered non-maximum suppression information so that this object can be reused again (for the same task with same resolution etc.).
262 * The allocated memory will remain so that reusing this object may improve performance.
263 */
264 void reset();
265
266 /**
267 * Move operator.
268 * @param nonMaximumSuppression Object to be moved
269 * @return Reference to this object
270 */
272
273 /**
274 * Copy operator.
275 * @param nonMaximumSuppression The object to be copied
276 * @return Reference to this object
277 */
278 NonMaximumSuppression<T>& operator=(const NonMaximumSuppression<T>& nonMaximumSuppression);
279
280 /**
281 * Applies a non-maximum-suppression based on already existing strength positions (just with a custom suppression radius) e.g., as a post-processing step.
282 * @param width The width of the image/domain in which the strength positions are located, e.g., in pixel, with range [1, infinity)
283 * @param height The height of the image/domain in which the strength positions are located, e.g., in pixel, with range [1, infinity)
284 * @param strengthPositions The strength positions for which a custom suppression-radius will be applied
285 * @param radius The suppression radius to be applied, with range [1, infinity)
286 * @param validIndices Optional resulting indices of all strength positions which remain after suppression
287 * @return The resulting strength positions
288 * @tparam TCoordinate The data type of a scalar coordinate
289 * @tparam TStrength The data type of the strength parameter
290 * @tparam tStrictMaximum True, to search for a strict maximum (larger than all eight neighbors); False, to allow equal values in the upper left neighborhood
291 */
292 template <typename TCoordinate, typename TStrength, bool tStrictMaximum>
293 static StrengthPositions<TCoordinate, TStrength> suppressNonMaximum(const unsigned int width, const unsigned int height, const StrengthPositions<TCoordinate, TStrength>& strengthPositions, const TCoordinate radius, Indices32* validIndices = nullptr);
294
295 /**
296 * Determines the precise peak location in 1D space for three discrete neighboring measurements at location x == 0.
297 * The precise peak is determined based on the first and second derivatives of the measurement values.
298 * @param leftValue The left discrete value, e.g., at location x - 1, with range (-infinity, middleValue]
299 * @param middleValue The middle discrete value, e.g., at location x, with range (-infinity, infinity)
300 * @param rightValue The discrete value, e.g., at location x + 1, with range (-infinity, middleValue]
301 * @param location The location of the precise peak of all values, with range (-1, 1)
302 * @return True, if succeeded
303 * @tparam TFloat The floating point data type to be used for calculation, either 'float' or 'double'
304 */
305 template <typename TFloat>
306 static bool determinePrecisePeakLocation1(const T& leftValue, const T& middleValue, const T& rightValue, TFloat& location);
307
308 /**
309 * Determines the precise peak location in 2D space for nine discrete neighboring measurements at location x == 0, y == 0.
310 * The precise peak is determined based on the first and second derivatives of the measurement values.
311 * @param topValues The three discrete values in the top row, must be valid
312 * @param centerValues The three discrete values in the center row, must be valid
313 * @param bottomValues The three discrete values in the bottom row, must be valid
314 * @param location The location of the precise peak of all values, with range (-1, 1)
315 * @return True, if succeeded
316 * @tparam TFloat The floating point data type to be used for calculation, either 'float' or 'double'
317 */
318 template <typename TFloat>
319 static bool determinePrecisePeakLocation2(const T* const topValues, const T* const centerValues, const T* const bottomValues, VectorT2<TFloat>& location);
320
321 private:
322
323 /**
324 * Adds new candidates to this object from a subset of a given buffer providing one value for each bin/pixel of this object.
325 * @param values The from which candidates will be added, must be width() * height() elements
326 * @param valuesStrideElements The number of elements between two values rows, in elements, with range [0, infinity)
327 * @param minimalThreshold The minimal threshold so that a value counts as candidate
328 * @param firstColumn First column to be handled, with range [0, width() - 1]
329 * @param numberColumns Number of columns to be handled, with range [1, width() - firstColumn]
330 * @param firstRow The first row in the buffer from which the candidates will be added, with range [yOffset(), height())
331 * @param numberRows The number of rows to be handled, with range [1, height() - firstRow]
332 * @see addCandidates().
333 */
334 void addCandidatesSubset(const T* values, const unsigned int valuesStrideElements, const unsigned int firstColumn, const unsigned int numberColumns, const T* minimalThreshold, const unsigned int firstRow, const unsigned int numberRows);
335
336 /**
337 * Applies a non-maximum-suppression search on a subset of a given 2D frame in a 3x3 neighborhood (eight neighbors).
338 * This function allows to determine the precise position of the individual maximum value positions by application of a callback function determining the individual positions.<br>
339 * @param strengthPositions Resulting non maximum suppressed positions including the strength parameters
340 * @param firstColumn First column to be handled
341 * @param numberColumns Number of columns to be handled
342 * @param lock The lock object that must be defined if this function is executed in parallel on several threads
343 * @param positionCallback Optional callback function allowing to determine the precise position of the individual maximum value positions
344 * @param firstRow First row to be handled
345 * @param numberRows Number of rows to be handled
346 * @tparam tStrictMaximum True, to search for a strict maximum (larger than all eight neighbors); False, to allow equal values in the upper left neighborhood
347 */
348 template <typename TCoordinate, typename TStrength, bool tStrictMaximum>
349 void suppressNonMaximumSubset(StrengthPositions<TCoordinate, TStrength>* strengthPositions, const unsigned int firstColumn, const unsigned int firstRow, Lock* lock, const PositionCallback<TCoordinate, TStrength>* positionCallback, const unsigned int numberColumns, const unsigned int numberRows) const;
350
351 private:
352
353 /// Width of this object.
354 unsigned int width_ = 0u;
355
356 /// All candidate rows.
358};
359
360template <typename T>
361template <typename TCoordinate, typename TStrength>
363 VectorT2<TCoordinate>(x, y),
364 strength_(strength)
365{
366 // nothing to do here
367}
368
369template <typename T>
370template <typename TCoordinate, typename TStrength>
372{
373 return strength_;
374}
375
376template <typename T>
377template <typename TCoordinate, typename TStrength>
378template <bool tLeftLargerThanRight>
380{
381 if constexpr (tLeftLargerThanRight)
382 {
383 return left.strength() > right.strength();
384 }
385 else
386 {
387 return left.strength() < right.strength();
388 }
389}
390
391template <typename T>
393 positionX_(-1),
394 strength_(T())
395{
396 // nothing to do here
397}
398
399template <typename T>
400inline NonMaximumSuppression<T>::StrengthCandidate::StrengthCandidate(const unsigned int x, const T& strength) :
401 positionX_(x),
402 strength_(strength)
403{
404 // nothing to do here
405}
406
407template <typename T>
409{
410 return positionX_;
411}
412
413template <typename T>
415{
416 return strength_;
417}
418
419template <typename T>
421{
422 *this = std::move(nonMaximumSuppression);
423}
424
425template <typename T>
427 width_(nonMaximumSuppression.width_),
428 rows_(nonMaximumSuppression.rows_)
429{
430 // nothing to do here
431}
432
433template <typename T>
434NonMaximumSuppression<T>::NonMaximumSuppression(const unsigned int width, const unsigned int height, const unsigned int yOffset) noexcept :
435 width_(width),
437{
438 // nothing to do here
439}
440
441template <typename T>
442inline unsigned int NonMaximumSuppression<T>::width() const
443{
444 return width_;
445}
446
447template <typename T>
448inline unsigned int NonMaximumSuppression<T>::height() const
449{
450 return (unsigned int)rows_.size();
451}
452
453template <typename T>
454inline unsigned int NonMaximumSuppression<T>::yOffset() const
455{
456 ocean_assert(rows_.firstIndex() >= 0);
457
458 return (unsigned int)(rows_.firstIndex());
459}
460
461template <typename T>
462inline void NonMaximumSuppression<T>::addCandidate(const unsigned int x, const unsigned int y, const T& strength)
463{
464 ocean_assert(x < width_);
465
466 ocean_assert(rows_.isValidIndex(y) && y >= (unsigned int)(rows_.firstIndex()) && y <= (unsigned int)(rows_.endIndex()));
467
468 if (rows_[y].empty())
469 {
470 rows_[y].reserve(128);
471 }
472
473 rows_[y].emplace_back(x, strength);
474}
475
476template <typename T>
477void NonMaximumSuppression<T>::addCandidates(const T* values, const unsigned int valuesPaddingElements, const unsigned int firstColumn, const unsigned int numberColumns, const unsigned int firstRow, const unsigned int numberRows, const T& minimalThreshold, Worker* worker)
478{
479 ocean_assert(values != nullptr);
480
481 ocean_assert(firstColumn + numberColumns <= width_);
482 ocean_assert(typename StrengthCandidateRows::Index(firstRow) >= rows_.firstIndex());
483 ocean_assert(typename StrengthCandidateRows::Index(firstRow + numberRows) <= rows_.endIndex());
484
485 const unsigned int valuesStrideElements = width_ + valuesPaddingElements;
486
487 if (worker)
488 {
489 worker->executeFunction(Worker::Function::create(*this, &NonMaximumSuppression<T>::addCandidatesSubset, values, valuesStrideElements, firstColumn, numberColumns, &minimalThreshold, 0u, 0u), firstRow, numberRows, 5u, 6u, 20u);
490 }
491 else
492 {
493 addCandidatesSubset(values, valuesStrideElements, firstColumn, numberColumns, &minimalThreshold, firstRow, numberRows);
494 }
495}
496
497template <typename T>
498inline void NonMaximumSuppression<T>::removeCandidatesRightFrom(const unsigned int x, const unsigned int y)
499{
500 ocean_assert(rows_.isValidIndex(y) && y >= (unsigned int)(rows_.firstIndex()) && y <= (unsigned int)(rows_.endIndex()));
501
502 StrengthCandidateRow& suppressionRow = rows_[y];
503
504 while (!suppressionRow.empty())
505 {
506 if (suppressionRow.back().x() >= x)
507 {
508 suppressionRow.pop_back();
509 }
510 else
511 {
512 break;
513 }
514 }
515}
516
517template <typename T>
518template <typename TCoordinate, typename TStrength, bool tStrictMaximum>
519typename NonMaximumSuppression<T>::template StrengthPositions<TCoordinate, TStrength> NonMaximumSuppression<T>::suppressNonMaximum(const unsigned int firstColumn, const unsigned int numberColumns, const unsigned int firstRow, const unsigned int numberRows, Worker* worker, const PositionCallback<TCoordinate, TStrength>* positionCallback) const
520{
521 ocean_assert(firstColumn + numberColumns <= width_);
522 ocean_assert(firstRow >= (unsigned int)rows_.firstIndex() && firstRow + numberRows <= (unsigned int)rows_.endIndex());
523
525 result.reserve(100);
526
527 if (worker)
528 {
529 Lock lock;
530 worker->executeFunction(Worker::Function::create(*this, &NonMaximumSuppression<T>::suppressNonMaximumSubset<TCoordinate, TStrength, tStrictMaximum>, &result, firstColumn, numberColumns, &lock, positionCallback, 0u, 0u), firstRow, numberRows, 5u, 6u, 3u);
531 }
532 else
533 {
534 suppressNonMaximumSubset<TCoordinate, TStrength, tStrictMaximum>(&result, firstColumn, numberColumns, nullptr, positionCallback, firstRow, numberRows);
535 }
536
537 return result;
538}
539
540template <typename T>
541void NonMaximumSuppression<T>::candidates(const unsigned int firstColumn, const unsigned int numberColumns, const unsigned int firstRow, const unsigned int numberRows, NonMaximumSuppression<T>::StrengthPositions<unsigned int, T>& strengthPositions)
542{
543 ocean_assert(firstColumn + numberColumns <= width_);
544 ocean_assert(firstRow + numberRows <= (unsigned int)(rows_.endIndex()));
545
546 const unsigned int endColumn = firstColumn + numberColumns;
547
548 for (unsigned int y = firstRow; y < firstRow + numberRows; ++y)
549 {
550 const StrengthCandidateRow& row = rows_[y];
551
552 for (const StrengthCandidate& candidate : row)
553 {
554 if (candidate.x() < firstColumn)
555 {
556 continue;
557 }
558
559 if (candidate.x() >= endColumn)
560 {
561 break;
562 }
563
564 strengthPositions.emplace_back(candidate.x(), y, candidate.strength());
565 }
566 }
567}
568
569template <typename T>
571{
572 for (ptrdiff_t n = rows_.firstIndex(); n < rows_.endIndex(); ++n)
573 {
574 rows_[n].clear();
575 }
576}
577
578template <typename T>
580{
581 if (this != &nonMaximumSuppression)
582 {
583 width_ = nonMaximumSuppression.width_;
584 nonMaximumSuppression.width_ = 0u;
585
586 rows_ = std::move(nonMaximumSuppression.rows_);
587 }
588
589 return *this;
590}
591
592template <typename T>
594{
595 if (this != &nonMaximumSuppression)
596 {
597 width_ = nonMaximumSuppression.width_;
598 rows_ = nonMaximumSuppression.rows_;
599 }
600
601 return *this;
602}
603
604template <typename T>
605template <typename TCoordinate, typename TStrength, bool tStrictMaximum>
607{
608 ocean_assert(width >= 1u && height >= 1u);
609 ocean_assert(radius >= TCoordinate(1));
610
611 const unsigned int binSize = std::max(10u, (unsigned int)(NumericT<TCoordinate>::ceil(radius)));
612
613 const unsigned int horizontalBins = std::max(1u, (width + binSize - 1u) / binSize);
614 const unsigned int verticalBins = std::max(1u, (height + binSize - 1u) / binSize);
615
616 ocean_assert(binSize * horizontalBins >= width);
617 ocean_assert(binSize * verticalBins >= height);
618
619 IndexGroups32 indexGroups(horizontalBins * verticalBins);
620
621 // distributing all strength positions into a regular grid to reduce search space later
622
623 for (size_t n = 0; n < strengthPositions.size(); ++n)
624 {
625 const VectorT2<TCoordinate>& position = strengthPositions[n];
626
627 ocean_assert((unsigned int)(position.x()) < width);
628 ocean_assert((unsigned int)(position.y()) < height);
629
630 const unsigned int xBin = (unsigned int)(position.x()) / binSize;
631 const unsigned int yBin = (unsigned int)(position.y()) / binSize;
632
633 ocean_assert(xBin <= horizontalBins);
634 ocean_assert(yBin <= verticalBins);
635
636 indexGroups[yBin * horizontalBins + xBin].emplace_back(Index32(n));
637 }
638
639 std::vector<uint8_t> validPositions(strengthPositions.size(), 1u);
640
641 const TCoordinate sqrRadius = radius * radius;
642
643 for (size_t nCandidate = 0; nCandidate < strengthPositions.size(); ++nCandidate)
644 {
645 if (validPositions[nCandidate] == 0u)
646 {
647 // the positions is already suppressed
648 continue;
649 }
650
651 const StrengthPosition<TCoordinate, TStrength>& candidatePosition = strengthPositions[nCandidate];
652
653 const unsigned int xCandidateBin = (unsigned int)(candidatePosition.x()) / binSize;
654 const unsigned int yCandidateBin = (unsigned int)(candidatePosition.y()) / binSize;
655
656 ocean_assert(xCandidateBin <= horizontalBins);
657 ocean_assert(yCandidateBin <= verticalBins);
658
659 bool checkNextCandidate = false;
660
661 for (unsigned int yBin = (unsigned int)(max(0, int(yCandidateBin) - 1)); !checkNextCandidate && yBin < min(yCandidateBin + 2u, verticalBins); ++yBin)
662 {
663 for (unsigned int xBin = (unsigned int)(max(0, int(xCandidateBin) - 1)); !checkNextCandidate && xBin < min(xCandidateBin + 2u, horizontalBins); ++xBin)
664 {
665 const Indices32& indices = indexGroups[yBin * horizontalBins + xBin];
666
667 for (const Index32& nTest : indices)
668 {
669 if (nTest == Index32(nCandidate))
670 {
671 continue;
672 }
673
674 const StrengthPosition<TCoordinate, TStrength>& testPosition = strengthPositions[nTest];
675
676 // we do not check whether test position is suppressed already (as the test position may still be the reason to suppress the candidate position)
677
678 if (candidatePosition.sqrDistance(testPosition) <= sqrRadius)
679 {
680 if (candidatePosition.strength() > testPosition.strength())
681 {
682 validPositions[nTest] = 0u;
683 }
684 else if (candidatePosition.strength() < testPosition.strength())
685 {
686 validPositions[nCandidate] = 0u;
687
688 checkNextCandidate = true;
689 break;
690 }
691 else
692 {
693 ocean_assert(candidatePosition.strength() == testPosition.strength());
694
695 if constexpr (tStrictMaximum)
696 {
697 // we suppress both elements, as we seek a strict maximum element
698
699 validPositions[nCandidate] = 0u;
700 validPositions[nTest] = 0u;
701
702 checkNextCandidate = true;
703 break;
704 }
705 else
706 {
707 // we will suppress one of both elements, as we accept a non-strict maximum element
708
709 if (candidatePosition.y() < testPosition.y() || (candidatePosition.y() == testPosition.y() && candidatePosition.x() < testPosition.x()))
710 {
711 // the candidate position will be suppressed as the test position is located to the bottom/right of the candidate position
712
713 validPositions[nCandidate] = 0u;
714
715 checkNextCandidate = true;
716 break;
717 }
718 else
719 {
720 ocean_assert(testPosition.y() < candidatePosition.y() || (testPosition.y() == candidatePosition.y() && testPosition.x() < candidatePosition.x()));
721
722 // the test position will be suppressed as the candidate position is located to the bottom/right of the test position
723
724 validPositions[nTest] = 0u;
725 }
726 }
727 }
728 }
729 }
730 }
731 }
732 }
733
735 remainingPositions.reserve(strengthPositions.size());
736
737 if (validIndices)
738 {
739 ocean_assert(validIndices->empty());
740
741 validIndices->clear();
742 validIndices->reserve(strengthPositions.size());
743
744 for (size_t n = 0; n < validPositions.size(); ++n)
745 {
746 if (validPositions[n])
747 {
748 remainingPositions.emplace_back(strengthPositions[n]);
749 validIndices->emplace_back(Index32(n));
750 }
751 }
752 }
753 else
754 {
755 for (size_t n = 0; n < validPositions.size(); ++n)
756 {
757 if (validPositions[n])
758 {
759 remainingPositions.emplace_back(strengthPositions[n]);
760 }
761 }
762 }
763
764 return remainingPositions;
765}
766
767template <typename T>
768template <typename TFloat>
769bool NonMaximumSuppression<T>::determinePrecisePeakLocation1(const T& leftValue, const T& middleValue, const T& rightValue, TFloat& location)
770{
771 static_assert(std::is_floating_point<TFloat>::value, "Invalid floating point data type!");
772
773 // f(x) = f(a) + f`(a) * (x - a)
774
775 // we expect our middle value to be located at a = 0:
776 // f(x) = f(0) + f`(0) * x
777
778 // 0 = f'(x)
779 // = f'(0) + f''(0) * x
780
781 // x = - f'(0) / f''(0)
782
783 // f`(x) = [-1 0 1] * 1/2
784 const TFloat df = (TFloat(rightValue) - TFloat(leftValue)) * TFloat(0.5);
785
786 // f``(x) = [1 -2 1] * 1/1
787 const TFloat dff = TFloat(leftValue) + TFloat(rightValue) - TFloat(middleValue) * TFloat(2);
788
790 {
791 location = TFloat(0);
792 return true;
793 }
794
795 const TFloat x = -df / dff;
796
797 if (x < TFloat(-1) || x > TFloat(1))
798 {
799 return false;
800 }
801
802 location = x;
803 return true;
804}
805
806template <typename T>
807template <typename TFloat>
808bool NonMaximumSuppression<T>::determinePrecisePeakLocation2(const T* const topValues, const T* const centerValues, const T* const bottomValues, VectorT2<TFloat>& location)
809{
810 static_assert(std::is_floating_point<TFloat>::value, "Invalid floating point data type!");
811
812 const T& value00 = topValues[0];
813 const T& value01 = topValues[1];
814 const T& value02 = topValues[2];
815
816 const T& value10 = centerValues[0];
817 const T& value11 = centerValues[1];
818 const T& value12 = centerValues[2];
819
820 const T& value20 = bottomValues[0];
821 const T& value21 = bottomValues[1];
822 const T& value22 = bottomValues[2];
823
824#if 0
825 // some response values may not perfectly follow the peak criteria so that we do not use the asserts by default
826 ocean_assert(value11 >= value00 && value11 >= value01 && value11 >= value02);
827 ocean_assert(value11 >= value10 && value11 >= value12);
828 ocean_assert(value11 >= value20 && value11 >= value21 && value11 >= value22);
829#endif
830
831 // [-1 0 1] * 1/2
832 const TFloat dx = TFloat(value12 - value10) * TFloat(0.5);
833 const TFloat dy = TFloat(value21 - value01) * TFloat(0.5);
834
835 // [1 -2 1] * 1/1
836 const TFloat dxx = TFloat(value12 + value10 - value11 * TFloat(2));
837 const TFloat dyy = TFloat(value21 + value01 - value11 * TFloat(2));
838
839 // [ 1 0 -1 ]
840 // [ 0 0 0 ] * 1/4
841 // [-1 0 1 ]
842
843 const TFloat dxy = TFloat(value22 + value00 - value20 - value02) * TFloat(0.25);
844
845 const TFloat denominator = dxx * dyy - dxy * dxy;
846
847 if (NumericT<TFloat>::isEqualEps(denominator))
848 {
849 location = VectorT2<TFloat>(0, 0);
850 return true;
851 }
852
853 const TFloat factor = TFloat(1) / denominator;
854
855 const TFloat offsetX = -(dyy * dx - dxy * dy) * factor;
856 const TFloat offsetY = -(dxx * dy - dxy * dx) * factor;
857
858 if (offsetX < TFloat(-1) || offsetX > TFloat(1) || offsetY < TFloat(-1) || offsetY > TFloat(1))
859 {
860 return false;
861 }
862
863 location = VectorT2<TFloat>(offsetX, offsetY);
864 return true;
865}
866
867template <typename T>
868void NonMaximumSuppression<T>::addCandidatesSubset(const T* values, const unsigned int valuesStrideElements, const unsigned int firstColumn, const unsigned int numberColumns, const T* minimalThreshold, const unsigned int firstRow, const unsigned int numberRows)
869{
870 ocean_assert(values != nullptr);
871 ocean_assert(valuesStrideElements >= width_);
872 ocean_assert(firstColumn + numberColumns <= width_);
873
874 ocean_assert(typename StrengthCandidateRows::Index(firstRow) >= rows_.firstIndex());
875 ocean_assert(typename StrengthCandidateRows::Index(firstRow + numberRows) <= rows_.endIndex());
876
877 const T localThreshold = *minimalThreshold;
878
879 values += firstRow * valuesStrideElements;
880
881 for (unsigned int y = firstRow; y < firstRow + numberRows; ++y)
882 {
883 for (unsigned int x = firstColumn; x < firstColumn + numberColumns; ++x)
884 {
885 if (values[x] >= localThreshold)
886 {
887 addCandidate(x, y, values[x]);
888 }
889 }
890
891 values += valuesStrideElements;
892 }
893}
894
895template <typename T>
896template <typename TCoordinate, typename TStrength, bool tStrictMaximum>
897void NonMaximumSuppression<T>::suppressNonMaximumSubset(StrengthPositions<TCoordinate, TStrength>* strengthPositions, const unsigned int firstColumn, const unsigned int numberColumns, Lock* lock, const PositionCallback<TCoordinate, TStrength>* positionCallback, const unsigned int firstRow, const unsigned int numberRows) const
898{
899 ocean_assert(strengthPositions);
900
901 ocean_assert(firstColumn + numberColumns <= width_);
902 ocean_assert(firstRow >= (unsigned int)rows_.firstIndex());
903 ocean_assert(firstRow + numberRows <= (unsigned int)rows_.endIndex());
904
905 if (numberColumns < 3u || numberRows < 3u)
906 {
907 return;
908 }
909
910 const unsigned int firstCenterColumn = max(1u, firstColumn);
911 const unsigned int endCenterColumn = min(firstColumn + numberColumns, width_ - 1u);
912
913 const unsigned int firstCenterRow = max((unsigned int)rows_.firstIndex() + 1u, firstRow);
914 const unsigned int endCenterRow = min(firstRow + numberRows, (unsigned int)rows_.lastIndex());
915
916 ocean_assert(firstCenterRow >= 1u);
917
918 StrengthPositions<TCoordinate, TStrength> localStrengthPositions;
919 localStrengthPositions.reserve(100);
920
921 for (unsigned int y = firstCenterRow; y < endCenterRow; ++y)
922 {
923 const StrengthCandidateRow& row0 = rows_[y - 1u];
924 const StrengthCandidateRow& row1 = rows_[y + 0u];
925 const StrengthCandidateRow& row2 = rows_[y + 1u];
926
927 typename StrengthCandidateRow::const_iterator i0 = row0.begin();
928 typename StrengthCandidateRow::const_iterator i2 = row2.begin();
929
930 typename StrengthCandidateRow::const_iterator i1Minus = row1.end();
931 typename StrengthCandidateRow::const_iterator i1Plus = row1.size() > 1 ? row1.begin() + 1 : row1.end();
932
933 for (typename StrengthCandidateRow::const_iterator i1 = row1.begin(); i1 != row1.end(); ++i1)
934 {
935 ocean_assert(i1->x() >= 0u && i1->x() + 1u <= width_);
936
937 // check left candidate (west)
938 if (i1->x() >= firstCenterColumn && i1->x() < endCenterColumn && (i1Minus == row1.end() || i1Minus->x() + 1u != i1->x() || (tStrictMaximum && i1Minus->strength() < i1->strength()) || (!tStrictMaximum && i1Minus->strength() <= i1->strength())))
939 {
940 // check right candidate (east)
941 if (i1Plus == row1.end() || i1Plus->x() != i1->x() + 1u || i1Plus->strength() < i1->strength())
942 {
943 // set the top row iterator to the right position
944 while (i0 != row0.end())
945 {
946 if (i0->x() + 1u < i1->x())
947 {
948 ++i0;
949 }
950 else
951 {
952 break;
953 }
954 }
955
956 // now i0 should point at least to the north west pixel position (or more far east)
957 ocean_assert(i0 == row0.end() || i0->x() + 1u >= i1->x());
958
959 if (i0 != row0.end() && i0->x() <= i1->x() + 1u)
960 {
961 ocean_assert(i0->x() + 1u == i1->x() || i0->x() == i1->x() || i0->x() - 1u == i1->x());
962
963 if ((tStrictMaximum && i0->strength() >= i1->strength()) || (!tStrictMaximum && i0->strength() > i1->strength()))
964 {
965 goto next;
966 }
967
968 // check if there is a further candidate in the north row
969
970 const typename StrengthCandidateRow::const_iterator i0Plus = i0 + 1;
971
972 if (i0Plus != row0.end() && i0Plus->x() <= i1->x() + 1u)
973 {
974 if ((tStrictMaximum && i0Plus->strength() >= i1->strength()) || (!tStrictMaximum && i0Plus->strength() > i1->strength()))
975 {
976 goto next;
977 }
978
979 // check if there is a further candidate in the north row
980
981 const typename StrengthCandidateRow::const_iterator i0PlusPlus = i0Plus + 1;
982
983 if (i0PlusPlus != row0.end() && i0PlusPlus->x() <= i1->x() + 1u)
984 {
985 ocean_assert(i0PlusPlus->x() == i1->x() + 1u);
986
987 if ((tStrictMaximum && i0PlusPlus->strength() >= i1->strength()) || (!tStrictMaximum && i0PlusPlus->strength() > i1->strength()))
988 {
989 goto next;
990 }
991 }
992 }
993 }
994
995
996 // set the bottom row iterator to the right position
997 while (i2 != row2.end())
998 {
999 if (i2->x() + 1u < i1->x())
1000 {
1001 ++i2;
1002 }
1003 else
1004 {
1005 break;
1006 }
1007 }
1008
1009 // now i2 should point at least to the south west pixel position (or more far east)
1010 ocean_assert(i2 == row2.end() || i2->x() + 1u >= i1->x());
1011
1012 if (i2 != row2.end() && i2->x() <= i1->x() + 1u)
1013 {
1014 ocean_assert(i2->x() + 1u == i1->x() || i2->x() == i1->x() || i2->x() - 1u == i1->x());
1015
1016 if (i2->x() + 1u == i1->x())
1017 {
1018 // i2 points to the south west pixel
1019
1020 if ((tStrictMaximum && i2->strength() >= i1->strength()) || (!tStrictMaximum && i2->strength() > i1->strength()))
1021 {
1022 goto next;
1023 }
1024 }
1025 else
1026 {
1027 if (i2->strength() >= i1->strength())
1028 {
1029 goto next;
1030 }
1031 }
1032
1033 // check if there is a further candidate in the south row
1034
1035 const typename StrengthCandidateRow::const_iterator i2Plus = i2 + 1;
1036
1037 if (i2Plus != row2.end() && i2Plus->x() <= i1->x() + 1u)
1038 {
1039 if (i2Plus->strength() >= i1->strength()) {
1040 goto next;
1041}
1042
1043 // check if there is a further candidate in the south row
1044
1045 const typename StrengthCandidateRow::const_iterator i2PlusPlus = i2Plus + 1;
1046
1047 if (i2PlusPlus != row2.end() && i2PlusPlus->x() <= i1->x() + 1u)
1048 {
1049 ocean_assert(i2PlusPlus->x() == i1->x() + 1u);
1050
1051 if (i2PlusPlus->strength() >= i1->strength()) {
1052 goto next;
1053}
1054 }
1055 }
1056 }
1057
1058 if (positionCallback)
1059 {
1060 TCoordinate preciseX, preciseY;
1061 TStrength preciseStrength;
1062 if ((*positionCallback)(i1->x(), y, i1->strength(), preciseX, preciseY, preciseStrength))
1063 {
1064 localStrengthPositions.emplace_back(preciseX, preciseY, preciseStrength);
1065 }
1066 }
1067 else
1068 {
1069 localStrengthPositions.emplace_back(TCoordinate(i1->x()), TCoordinate(y), i1->strength());
1070 }
1071 }
1072 }
1073
1074next:
1075
1076 i1Minus = i1;
1077
1078 if (i1Plus != row1.end()) {
1079 ++i1Plus;
1080}
1081 }
1082 }
1083
1084 const OptionalScopedLock scopedLock(lock);
1085
1086 strengthPositions->insert(strengthPositions->end(), localStrengthPositions.begin(), localStrengthPositions.end());
1087}
1088
1089}
1090
1091}
1092
1093#endif // META_OCEAN_CV_NON_MAXIMUM_SUPPRESSION_H
This class holds the horizontal position and strength parameter of an interest pixel.
Definition NonMaximumSuppression.h:114
StrengthCandidate()
Creates a new candidate object.
Definition NonMaximumSuppression.h:392
const T & strength() const
Returns the strength parameter of this object.
Definition NonMaximumSuppression.h:414
unsigned int x() const
Returns the horizontal position of this candidate object.
Definition NonMaximumSuppression.h:408
T strength_
Strength parameter of this object.
Definition NonMaximumSuppression.h:147
unsigned int positionX_
Horizontal position of this object.
Definition NonMaximumSuppression.h:144
This class extends a 2D position by a third parameter storing a strength value.
Definition NonMaximumSuppression.h:51
static bool compareStrength(const StrengthPosition< TCoordinate, TStrength > &left, const StrengthPosition< TCoordinate, TStrength > &right)
Compares the strength value of two objects.
Definition NonMaximumSuppression.h:379
StrengthPosition()=default
Creates a new object with default strength parameter.
const TStrength & strength() const
Returns the strength parameter of this object.
Definition NonMaximumSuppression.h:371
TStrength strength_
Strength parameter of this object.
Definition NonMaximumSuppression.h:86
This class implements the possibility to find local maximum in a 2D array by applying a non-maximum-s...
Definition NonMaximumSuppression.h:41
NonMaximumSuppression< T > & operator=(NonMaximumSuppression< T > &&nonMaximumSuppression)
Move operator.
Definition NonMaximumSuppression.h:579
StrengthPositions< TCoordinate, TStrength > suppressNonMaximum(const unsigned int firstColumn, const unsigned int numberColumns, const unsigned int firstRow, const unsigned int numberRows, Worker *worker=nullptr, const PositionCallback< TCoordinate, TStrength > *positionCallback=nullptr) const
Applies a non-maximum-suppression search on a given 2D frame in a 3x3 neighborhood (eight neighbors).
unsigned int width_
Width of this object.
Definition NonMaximumSuppression.h:354
StrengthCandidateRows rows_
All candidate rows.
Definition NonMaximumSuppression.h:357
void candidates(const unsigned int firstColumn, const unsigned int numberColumns, const unsigned int firstRow, const unsigned int numberRows, StrengthPositions< unsigned int, T > &strengthPositions)
Returns all gathered candidates of this object.
Definition NonMaximumSuppression.h:541
static bool determinePrecisePeakLocation1(const T &leftValue, const T &middleValue, const T &rightValue, TFloat &location)
Determines the precise peak location in 1D space for three discrete neighboring measurements at locat...
Definition NonMaximumSuppression.h:769
void reset()
Removes the gathered non-maximum suppression information so that this object can be reused again (for...
Definition NonMaximumSuppression.h:570
unsigned int height() const
Returns the height of this object.
Definition NonMaximumSuppression.h:448
unsigned int yOffset() const
Returns the optional offset in the vertical direction.
Definition NonMaximumSuppression.h:454
void suppressNonMaximumSubset(StrengthPositions< TCoordinate, TStrength > *strengthPositions, const unsigned int firstColumn, const unsigned int firstRow, Lock *lock, const PositionCallback< TCoordinate, TStrength > *positionCallback, const unsigned int numberColumns, const unsigned int numberRows) const
Applies a non-maximum-suppression search on a subset of a given 2D frame in a 3x3 neighborhood (eight...
Definition NonMaximumSuppression.h:897
void addCandidatesSubset(const T *values, const unsigned int valuesStrideElements, const unsigned int firstColumn, const unsigned int numberColumns, const T *minimalThreshold, const unsigned int firstRow, const unsigned int numberRows)
Adds new candidates to this object from a subset of a given buffer providing one value for each bin/p...
Definition NonMaximumSuppression.h:868
void removeCandidatesRightFrom(const unsigned int x, const unsigned int y)
Removes all candidates from a specified row having a horizontal location equal or larger than a speci...
Definition NonMaximumSuppression.h:498
std::vector< StrengthPosition< TCoordinate, TStrength > > StrengthPositions
Definition of a vector holding strength pixel positions.
Definition NonMaximumSuppression.h:93
void addCandidate(const unsigned int x, const unsigned int y, const T &strength)
Adds a new candidate to this object.
Definition NonMaximumSuppression.h:462
static bool determinePrecisePeakLocation2(const T *const topValues, const T *const centerValues, const T *const bottomValues, VectorT2< TFloat > &location)
Determines the precise peak location in 2D space for nine discrete neighboring measurements at locati...
Definition NonMaximumSuppression.h:808
unsigned int width() const
Returns the width of this object.
Definition NonMaximumSuppression.h:442
NonMaximumSuppression(NonMaximumSuppression< T > &&nonMaximumSuppression) noexcept
Move constructor.
Definition NonMaximumSuppression.h:420
static StrengthPositions< TCoordinate, TStrength > suppressNonMaximum(const unsigned int width, const unsigned int height, const StrengthPositions< TCoordinate, TStrength > &strengthPositions, const TCoordinate radius, Indices32 *validIndices=nullptr)
Applies a non-maximum-suppression based on already existing strength positions (just with a custom su...
std::vector< StrengthCandidate > StrengthCandidateRow
Definition of a vector holding strength candidate objects.
Definition NonMaximumSuppression.h:153
void addCandidates(const T *values, const unsigned int valuesPaddingElements, const unsigned int firstColumn, const unsigned int numberColumns, const unsigned int firstRow, const unsigned int numberRows, const T &minimalThreshold, Worker *worker)
Adds new candidates to this object from a given buffer providing one value for each bin/pixel of this...
Definition NonMaximumSuppression.h:477
This class implements a container for callback functions.
Definition Callback.h:3456
static Caller< void > create(CT &object, typename MemberFunctionPointerMaker< CT, void, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass, NullClass >::Type function)
Creates a new caller container for a member function with no function parameter.
Definition Caller.h:3024
This class implements a recursive lock object.
Definition Lock.h:31
This class provides basic numeric functionalities.
Definition Numeric.h:57
This class implements an optional recursive scoped lock object locking the lock object only if it's d...
Definition Lock.h:325
bool isValidIndex(const Index index) const
Returns whether a specific index is valid for this vector and matches to the current offset layout.
Definition ShiftVector.h:646
size_t size() const
Returns the number of elements that are stored by this object.
Definition ShiftVector.h:490
Index endIndex() const
Returns the index of the element behind the last (excluding) element of this object.
Definition ShiftVector.h:435
void clear()
Clears this object, the specified index shift will be untouched.
Definition ShiftVector.h:658
std::ptrdiff_t Index
Definition of an element index.
Definition ShiftVector.h:38
Iterator begin()
Returns the iterator for the first data element.
Definition ShiftVector.h:670
Index lastIndex() const
Returns the index of the last (including) element of this object.
Definition ShiftVector.h:422
Index firstIndex() const
Returns the index of the first element of this object.
Definition ShiftVector.h:416
This class implements a vector with two elements.
Definition Vector2.h:96
const TCoordinate & x() const noexcept
Returns the x value.
Definition Vector2.h:710
const TCoordinate & y() const noexcept
Returns the y value.
Definition Vector2.h:722
T sqrDistance(const VectorT2< T > &right) const
Returns the square distance between this 2D position and a second 2D position.
Definition Vector2.h:645
This class implements a worker able to distribute function calls over different threads.
Definition Worker.h:33
bool executeFunction(const Function &function, const unsigned int first, const unsigned int size, const unsigned int firstIndex=(unsigned int)(-1), const unsigned int sizeIndex=(unsigned int)(-1), const unsigned int minimalIterations=1u, const unsigned int threadIndex=(unsigned int)(-1))
Executes a callback function separable by two function parameters.
std::vector< Indices32 > IndexGroups32
Definition of a vector holding 32 bit indices, so we have groups of indices.
Definition Base.h:102
std::vector< Index32 > Indices32
Definition of a vector holding 32 bit index values.
Definition Base.h:96
uint32_t Index32
Definition of a 32 bit index value.
Definition Base.h:84
The namespace covering the entire Ocean framework.
Definition Accessor.h:15