You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3392 lines
110 KiB

8 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /** @file covdet.c
  2. ** @brief Covariant feature detectors - Definition
  3. ** @author Karel Lenc
  4. ** @author Andrea Vedaldi
  5. ** @author Michal Perdoch
  6. **/
  7. /*
  8. Copyright (C) 2013-14 Andrea Vedaldi.
  9. Copyright (C) 2012 Karel Lenc, Andrea Vedaldi and Michal Perdoch.
  10. All rights reserved.
  11. This file is part of the VLFeat library and is made available under
  12. the terms of the BSD license (see the COPYING file).
  13. */
  14. /**
  15. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  16. @page covdet Covariant feature detectors
  17. @author Karel Lenc
  18. @author Andrea Vedaldi
  19. @author Michal Perdoch
  20. @tableofcontents
  21. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  22. @ref covdet.h implements a number of covariant feature detectors, based
  23. on three cornerness measures (determinant of the Hessian, trace of the Hessian
  24. (aka Difference of Gaussians, and Harris). It supprots affine adaptation,
  25. orientation estimation, as well as Laplacian scale detection.
  26. - @subpage covdet-fundamentals
  27. - @subpage covdet-principles
  28. - @subpage covdet-differential
  29. - @subpage covdet-corner-types
  30. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  31. @section covdet-starting Getting started
  32. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  33. The ::VlCovDet object implements a number of covariant feature
  34. detectors: Difference of Gaussian, Harris, determinant of Hessian.
  35. Variant of the basic detectors support scale selection by maximizing
  36. the Laplacian measure as well as affine normalization.
  37. @code
  38. // create a detector object
  39. VlCovDet * covdet = vl_covdet_new(method) ;
  40. // set various parameters (optional)
  41. vl_covdet_set_first_octave(covdet, -1) ; // start by doubling the image resolution
  42. vl_covdet_set_octave_resolution(covdet, octaveResolution) ;
  43. vl_covdet_set_peak_threshold(covdet, peakThreshold) ;
  44. vl_covdet_set_edge_threshold(covdet, edgeThreshold) ;
  45. // process the image and run the detector
  46. vl_covdet_put_image(covdet, image, numRows, numCols) ;
  47. vl_covdet_detect(covdet) ;
  48. // drop features on the margin (optional)
  49. vl_covdet_drop_features_outside (covdet, boundaryMargin) ;
  50. // compute the affine shape of the features (optional)
  51. vl_covdet_extract_affine_shape(covdet) ;
  52. // compute the orientation of the features (optional)
  53. vl_covdet_extract_orientations(covdet) ;
  54. // get feature frames back
  55. vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
  56. VlCovDetFeature const * feature = vl_covdet_get_features(covdet) ;
  57. // get normalized feature appearance patches (optional)
  58. vl_size w = 2*patchResolution + 1 ;
  59. for (i = 0 ; i < numFeatures ; ++i) {
  60. float * patch = malloc(w*w*sizeof(*desc)) ;
  61. vl_covdet_extract_patch_for_frame(covdet,
  62. patch,
  63. patchResolution,
  64. patchRelativeExtent,
  65. patchRelativeSmoothing,
  66. feature[i].frame) ;
  67. // do something with patch
  68. }
  69. @endcode
  70. This example code:
  71. - Calls ::vl_covdet_new constructs a new detector object. @ref
  72. covdet.h supports a variety of different detectors (see
  73. ::VlCovDetMethod).
  74. - Optionally calls various functions to set the detector parameters if
  75. needed (e.g. ::vl_covdet_set_peak_threshold).
  76. - Calls ::vl_covdet_put_image to start processing a new image. It
  77. causes the detector to compute the scale space representation of the
  78. image, but does not compute the features yet.
  79. - Calls ::vl_covdet_detect runs the detector. At this point features are
  80. ready to be extracted. However, one or all of the following steps
  81. may be executed in order to process the features further.
  82. - Optionally calls ::vl_covdet_drop_features_outside to drop features
  83. outside the image boundary.
  84. - Optionally calls ::vl_covdet_extract_affine_shape to compute the
  85. affine shape of features using affine adaptation.
  86. - Optionally calls ::vl_covdet_extract_orientations to compute the
  87. dominant orientation of features looking for the dominant gradient
  88. orientation in patches.
  89. - Optionally calls ::vl_covdet_extract_patch_for_frame to extract a
  90. normalized feature patch, for example to compute an invariant
  91. feature descriptor.
  92. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  93. @page covdet-fundamentals Covariant detectors fundamentals
  94. @tableofcontents
  95. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  96. This page describes the fundamental concepts required to understand a
  97. covariant feature detector, the geometry of covariant features, and
  98. the process of feature normalization.
  99. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  100. @section covdet-covariance Covariant detection
  101. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  102. The purpose of a *covariant detector* is to extract from an image a
  103. set of local features in a manner which is consistent with spatial
  104. transformations of the image itself. For instance, a covariant
  105. detector that extracts interest points $\bx_1,\dots,\bx_n$ from image
  106. $\ell$ extracts the translated points $\bx_1+T,\dots,\bx_n+T$ from the
  107. translated image $\ell'(\bx) = \ell(\bx-T)$.
  108. More in general, consider a image $\ell$ and a transformed version
  109. $\ell' = \ell \circ w^{-1}$ of it, as in the following figure:
  110. @image html covdet.png "Covariant detection of local features."
  111. The transformation or <em>warp</em> $w : \real^2 \mapsto \real^2$ is a
  112. deformation of the image domain which may capture a change of camera
  113. viewpoint or similar imaging factor. Examples of warps typically
  114. considered are translations, scaling, rotations, and general affine
  115. transformations; however, in $w$ could be another type of continuous
  116. and invertible transformation.
  117. Given an image $\ell$, a **detector** selects features $R_1,\dots,R_n$
  118. (one such features is shown in the example as a green circle). The
  119. detector is said to be **covariant** with the warps $w$ if it extracts
  120. the transformed features $w[R_1],\dots, w[R_n]$ from the transformed
  121. image $w[\ell]$. Intuitively, this means that the &ldquo;same
  122. features&rdquo; are extracted in both cases up to the transformation
  123. $w$. This property is described more formally in @ref
  124. covdet-principles.
  125. Covariance is a key property of local feature detectors as it allows
  126. extracting corresponding features from two or more images, making it
  127. possible to match them in a meaningful way.
  128. The @ref covdet.h module in VLFeat implements an array of feature
  129. detection algorithm that have are covariant to different classes of
  130. transformations.
  131. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  132. @section covdet-frame Feature geometry and feature frames
  133. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  134. As we have seen, local features are subject to image transformations,
  135. and they apply a fundamental role in matching and normalizing
  136. images. To operates effectively with local features is therefore
  137. necessary to understand their geometry.
  138. The geometry of a local feature is captured by a <b>feature frame</b>
  139. $R$. In VLFeat, depending on the specific detector, the frame can be
  140. either a point, a disc, an ellipse, an oriented disc, or an oriented
  141. ellipse.
  142. A frame captures both the extent of the local features, useful to know
  143. which portions of two images are put in correspondence, as well their
  144. shape. The latter can be used to associate to diagnose the
  145. transformation that affects a feature and remove it through the
  146. process of **normalization**.
  147. More precisely, in covariant detection feature frames are constructed
  148. to be compatible with a certain class of transformations. For example,
  149. circles are compatible with similarity transformations as they are
  150. closed under them. Likewise, ellipses are compatible with affine
  151. transformations.
  152. Beyond this closure property, the key idea here is that all feature
  153. occurrences can be seen as transformed versions of a base or
  154. <b>canonical</b> feature. For example, all discs $R$ can be obtained
  155. by applying a similarity transformation to the unit disc $\bar R$
  156. centered at the origin. $\bar R$ is an example of canonical frame
  157. as any other disc can be written as $R = w[\bar R]$ for a suitable
  158. similarity $w$.
  159. @image html frame-canonical.png "The idea of canonical frame and normalization"
  160. The equation $R = w[\bar R_0]$ matching the canonical and detected
  161. feature frames establishes a constraint on the warp $w$, very similar
  162. to the way two reference frames in geometry establish a transformation
  163. between spaces. The transformation $w$ can be thought as a the
  164. **pose** of the detected feature, a generalization of its location.
  165. In the case of discs and similarity transformations, the equation $R =
  166. w[\bar R_0]$ fixes $w$ up to a residual rotation. This can be
  167. addressed by considering oriented discs instead. An **oriented disc**
  168. is a disc with a radius highlighted to represent the feature
  169. orientation.
  170. While discs are appropriate for similarity transformations, they are
  171. not closed under general affine transformations. In this case, one
  172. should consider the more general class of (oriented) ellipses. The
  173. following image illustrates the five types of feature frames used in
  174. VLFeat:
  175. @image html frame-types.png "Types of local feature frames: points, discs, oriented discs, ellipses, oriented ellipses."
  176. Note that these frames are described respectively by 2, 3, 4, 5 and 6
  177. parameters. The most general type are the oriented ellipses, which can
  178. be used to represent all the other frame types as well.
  179. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  180. @section covdet-frame-transformation Transforming feature frames
  181. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  182. Consider a warp $w$ mapping image $\ell$ into image $\ell'$ as in the
  183. figure below. A feature $R$ in the first image co-variantly transform
  184. into a feature $R'=w[R]$ in the second image:
  185. @image html covdet-normalization.png "Normalization removes the effect of an image deformation."
  186. The poses $u,u'$ of $R=u[R_0]$ and $R' = u'[R_0]$ are then related by
  187. the simple expression:
  188. \[
  189. u' = w \circ u.
  190. \]
  191. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  192. @section covdet-frame-normalization Normalizing feature frames
  193. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  194. In the example above, the poses $u$ and $u'$ relate the two
  195. occurrences $R$ and $R'$ of the feature to its canonical version
  196. $R_0$. If the pose $u$ of the feature in image $\ell$ is known, the
  197. canonical feature appearance can be computed by un-warping it:
  198. \[
  199. \ell_0 = u^{-1}[\ell] = \ell \circ u.
  200. \]
  201. This process is known as **normalization** and is the key in the
  202. computation of invariant feature descriptors as well as in the
  203. construction of most co-variant detectors.
  204. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  205. @page covdet-principles Principles of covariant detection
  206. @tableofcontents
  207. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  208. The goals of a co-variant detector were discussed in @ref
  209. covdet-fundamentals. This page introduces a few general principles
  210. that are at the basis of most covariant detection algorithms. Consider
  211. an input image $\ell$ and a two dimensional continuous and invertible
  212. warp $w$. The *warped image* $w[\ell]$ is defined to be
  213. \[
  214. w[\ell] = \ell \circ w^{-1},
  215. \]
  216. or, equivalently,
  217. \[
  218. w[\ell](x,y) = \ell(w^{-1}(x,y)), \qquad \forall (x,y)\in\real^2.
  219. \]
  220. Note that, while $w$ pushes pixels forward, from the original to the
  221. transformed image domain, defining the transformed image $\ell'$
  222. requires inverting the warp and composing $\ell$ with $w^{-1}$.
  223. The goal a covariant detector is to extract the same local features
  224. irregardless of image transformations. The detector is said to be
  225. <b>covariant</b> or <b>equivariant</b> with a class of warps
  226. $w\in\mathcal{W}$ if, when the feature $R$ is detected in image
  227. $\ell$, then the transformed feature $w[R]$ is detected in the
  228. transformed image $w[\ell]$.
  229. The net effect is that a covariant feature detector appears to
  230. &ldquo;track&rdquo; image transformations; however, it is important to
  231. note that a detector *is not a tracker* because it processes images
  232. individually rather than jointly as part of a sequence.
  233. An intuitive way to construct a covariant feature detector is to
  234. extract features in correspondence of images structures that are
  235. easily identifiable even after a transformation. Example of specific
  236. structures include dots, corners, and blobs. These will be generically
  237. indicated as **corners** in the followup.
  238. A covariant detector faces two challenges. First, corners have, in
  239. practice, an infinite variety of individual appearances and the
  240. detector must be able to capture them to be of general applicability.
  241. Second, the way corners are identified and detected must remain stable
  242. under transformations of the image. These two problems are addressed
  243. in @ref covdet-cornerness-localmax and @ref
  244. covdet-cornerness-normalization respectively.
  245. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  246. @section covdet-cornerness Detection using a cornerness measure
  247. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  248. One way to decide whether an image region $R$ contains a corner is to
  249. compare the local appearance to a model or template of the corner; the
  250. result of this comparisons produces a *cornerness score* at that
  251. location. This page describe general theoretical properties of the
  252. cornerness and the detection process. Concrete examples of cornerness
  253. are given in @ref covdet-corner-types.
  254. A **cornerness measure** associate a score to all possible feature
  255. locations in an image $\ell$. As described in @ref covdet-frame, the
  256. location or, more in general, pose $u$ of a feature $R$ is the warp
  257. $w$ that maps the canonical feature frame $R_0$ to $R$:
  258. \[
  259. R = u[R_0].
  260. \]
  261. The goal of a cornerness measure is to associate a score $F(u;\ell)$
  262. to all possible feature poses $u$ and use this score to extract a
  263. finite number of co-variant features from any image.
  264. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  265. @subsection covdet-cornerness-localmax Local maxima of a cornerness measure
  266. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  267. Given the cornerness of each candidate feature, the detector must
  268. extract a finite number of them. However, the cornerness of features
  269. with nearly identical pose must be similar (otherwise the cornerness
  270. measure would be unstable). As such, simply thresholding $F(w;\ell)$
  271. would detect an infinite number of nearly identical features rather
  272. than a finite number.
  273. The solution is to detect features in correspondence of the local
  274. maxima of the score measure:
  275. \[
  276. \{w_1,\dots,w_n\} = \operatorname{localmax}_{w\in\mathcal{W}} F(w;\ell).
  277. \]
  278. This also means that features are never detected in isolation, but by
  279. comparing neighborhoods of them.
  280. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  281. @subsection covdet-cornerness-normalization Covariant detection by normalization
  282. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  283. The next difficulty is to guarantee that detection is co-variant with
  284. image transformations. Hence, if $u$ is the pose of a feature
  285. extracted from image $\ell$, then the transformed pose $u' = w[u]$
  286. must be detected in the transformed image $\ell' = w[\ell]$.
  287. Since features are extracted in correspondence of the local maxima of
  288. the cornerness score, a sufficient condition is that corresponding
  289. features attain the same score in the two images:
  290. \[
  291. \forall u\in\mathcal{W}: \quad F(u;\ell) = F(w[u];w[\ell]),
  292. \qquad\text{or}\qquad
  293. F(u;\ell) = F(w \circ u ;\ell \circ w^{-1}).
  294. \]
  295. One simple way to satisfy this equation is to compute a cornerness
  296. score *after normalizing the image* by the inverse of the candidate
  297. feature pose warp $u$, as follows:
  298. \[
  299. F(u;\ell) = F(1;u^{-1}[\ell]) = F(1;\ell \circ u) = \mathcal{F}(\ell \circ u),
  300. \]
  301. where $1 = u^{-1} \circ u$ is the identity transformation and
  302. $\mathcal{F}$ is an arbitrary functional. Intuitively, co-variant
  303. detection is obtained by looking if the appearance of the feature
  304. resembles a corner only *after normalization*. Formally:
  305. @f{align*}
  306. F(w[u];w[\ell])
  307. &=
  308. F(w \circ u ;\ell \circ w^{-1})
  309. \\
  310. &=
  311. F(1; \ell \circ w^{-1} \circ w \circ u)
  312. \\
  313. &=
  314. \mathcal{F}(\ell\circ u)
  315. \\
  316. &=
  317. F(u;\ell).
  318. @f}
  319. Concrete examples of the functional $\mathcal{F}$ are given in @ref
  320. covdet-corner-types.
  321. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  322. @subsection covdet-locality Locality of the detected features
  323. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  324. In the definition above, the cornenress functional $\mathcal{F}$ is an
  325. arbitrary functional of the entire normalized image $u^{-1}[\ell]$.
  326. In practice, one is always interested in detecting **local features**
  327. (at the very least because the image extent is finite).
  328. This is easily obtained by considering a cornerness $\mathcal{F}$
  329. which only looks in a small region of the normalized image, usually
  330. corresponding to the extent of the canonical feature $R_0$ (e.g. a
  331. unit disc centered at the origin).
  332. In this case the extent of the local feature in the original image is
  333. simply given by $R = u[R_0]$.
  334. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  335. @section covdet-partial Partial and iterated normalization
  336. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  337. Practical detectors implement variants of the ideas above. Very often,
  338. for instance, detection is an iterative process, in which successive
  339. parameters of the pose of a feature are determined. For instance, it
  340. is typical to first detect the location and scale of a feature using a
  341. rotation-invariant cornerness score $\mathcal{F}$. Once these two
  342. parameters are known, the rotation can be determined using a different
  343. score, sensitive to the orientation of the local image structures.
  344. Certain detectors (such as Harris-Laplace and Hessian-Laplace) use
  345. even more sophisticated schemes, in which different scores are used to
  346. jointly (rather than in succession) different parameters of the pose
  347. of a feature, such as its translation and scale. While a formal
  348. treatment of these cases is possible as well, we point to the original
  349. papers.
  350. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  351. @page covdet-differential Differential and integral image operations
  352. @tableofcontents
  353. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  354. Dealing with covariant interest point detector requires working a good
  355. deal with derivatives, convolutions, and transformations of images.
  356. The notation and fundamental properties of interest here are discussed
  357. next.
  358. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  359. @section covdet-derivatives Derivative operations: gradients
  360. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  361. For the derivatives, we borrow the notation of
  362. @cite{kinghorn96integrals}. Let $f: \mathbb{R}^m \rightarrow
  363. \mathbb{R}^n, \bx \mapsto f(\bx)$ be a vector function. The derivative
  364. of the function with respect to $\bx$ is given by its *Jacobian
  365. matrix* denoted by the symbol:
  366. \[
  367. \frac{\partial f}{\partial \bx^\top}
  368. =
  369. \begin{bmatrix}
  370. \frac{\partial f_1}{x_1} & \frac{\partial f_1}{x_2} & \dots \\
  371. \frac{\partial f_2}{x_1} & \frac{\partial f_2}{x_2} & \dots \\
  372. \vdots & \vdots & \ddots \\
  373. \end{bmatrix}.
  374. \]
  375. When the function $ f $ is scalar ($n=1$), the Jacobian is the same as
  376. the gradient of the function (or, in fact, its transpose). More
  377. precisely, the <b>gradient</b> $\nabla f $ of $ f $ denotes the column
  378. vector of partial derivatives:
  379. \[
  380. \nabla f
  381. = \frac{\partial f}{\partial \bx}
  382. =
  383. \begin{bmatrix}
  384. \frac{\partial f}{\partial x_1} \\
  385. \frac{\partial f}{\partial x_2} \\
  386. \vdots
  387. \end{bmatrix}.
  388. \]
  389. The second derivative $H_f $ of a scalar function $ f $, or
  390. <b>Hessian</b>, is denoted as
  391. \[
  392. H_f
  393. = \frac{\partial f}{\partial \bx \partial \bx^\top}
  394. = \frac{\partial \nabla f}{\partial \bx^\top}
  395. =
  396. \begin{bmatrix}
  397. \frac{\partial f}{\partial x_1 \partial x_1} & \frac{\partial f}{\partial x_1 \partial x_2} & \dots \\
  398. \frac{\partial f}{\partial x_2 \partial x_1} & \frac{\partial f}{\partial x_2 \partial x_2} & \dots \\
  399. \vdots & \vdots & \ddots \\
  400. \end{bmatrix}.
  401. \]
  402. The determinant of the Hessian is also known as <b>Laplacian</b> and denoted as
  403. \[
  404. \Delta f = \operatorname{det} H_f =
  405. \frac{\partial f}{\partial x_1^2} +
  406. \frac{\partial f}{\partial x_2^2} +
  407. \dots
  408. \]
  409. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  410. @subsection covdet-derivative-transformations Derivative and image warps
  411. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  412. In the following, we will often been interested in domain warpings $u:
  413. \mathbb{R}^m \rightarrow \mathbb{R}^n, \bx \mapsto u(\bx)$ of a
  414. function $f(\bar\bx) $ and its effect on the derivatives of the
  415. function. The key transformation is the chain rule:
  416. \[
  417. \frac{\partial f \circ u}{\partial \bx^\top}
  418. =
  419. \left(\frac{\partial f}{\partial \bar\bx^\top} \circ u\right)
  420. \frac{\partial u}{\partial \bx^\top}
  421. \]
  422. In particular, for an affine transformation $u = (A,T) : \bx \mapsto
  423. A\bx + T$, one obtains the transformation rules:
  424. \[
  425. \begin{align*}
  426. \frac{\partial f \circ (A,T)}{\partial \bx^\top}
  427. &=
  428. \left(\frac{\partial f}{\partial \bar\bx^\top} \circ (A,T)\right)A,
  429. \\
  430. \nabla (f \circ (A,T))
  431. &= A^\top (\nabla f) \circ (A,T),
  432. \\
  433. H_{f \circ(A,T)}
  434. &= A^\top (H_f \circ (A,T)) A,
  435. \\
  436. \Delta (f \circ(A,T))
  437. &= \det(A)^2\, (\Delta f) \circ (A,T).
  438. \end{align*}
  439. \]
  440. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  441. @section covdet-smoothing Integral operations: smoothing
  442. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  443. In practice, given an image $\ell$ expressed in digital format, good
  444. derivative approximations can be computed only if the bandwidth of the
  445. image is limited and, in particular, compatible with the sampling
  446. density. Since it is unreasonable to expect real images to be
  447. band-limited, the bandwidth is artificially constrained by suitably
  448. smoothing the image prior to computing its derivatives. This is also
  449. interpreted as a form of regularization or as a way of focusing on the
  450. image content at a particular scale.
  451. Formally, we will focus on Gaussian smoothing kernels. For the 2D case
  452. $\bx\in\real^2$, the Gaussian kernel of covariance $\Sigma$ is given
  453. by
  454. \[
  455. g_{\Sigma}(\bx) = \frac{1}{2\pi \sqrt{\det\Sigma}}
  456. \exp\left(
  457. - \frac{1}{2} \bx^\top \Sigma^{-1} \bx
  458. \right).
  459. \]
  460. The symbol $g_{\sigma^2}$ will be used to denote a Gaussian kernel
  461. with isotropic standard deviation $\sigma$, i.e. $\Sigma = \sigma^2
  462. I$. Given an image $\ell$, the symbol $\ell_\Sigma$ will be used to
  463. denote the image smoothed by the Gaussian kernel of parameter
  464. $\Sigma$:
  465. \[
  466. \ell_\Sigma(\bx) = (g_\Sigma * \ell)(\bx)
  467. =
  468. \int_{\real^m}
  469. g_\Sigma(\bx - \by) \ell(\by)\,d\by.
  470. \]
  471. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  472. @subsection covdet-smoothing-transformations Smoothing and image warps
  473. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  474. One advantage of Gaussian kernels is that they are (up to
  475. renormalization) closed under a linear warp:
  476. \[
  477. |A|\, g_\Sigma \circ A = g_{A^{-1} \Sigma A^{-\top}}
  478. \]
  479. This also means that smoothing a warped image is the same as warping
  480. the result of smoothing the original image by a suitably adjusted
  481. Gaussian kernel:
  482. \[
  483. g_{\Sigma} * (\ell \circ (A,T))
  484. =
  485. (g_{A\Sigma A^\top} * \ell) \circ (A,T).
  486. \]
  487. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  488. @page covdet-corner-types Cornerness measures
  489. @tableofcontents
  490. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  491. The goal of a cornerness measure (@ref covdet-cornerness) is to
  492. associate to an image patch a score proportional to how strongly the
  493. patch contain a certain strucuture, for example a corner or a
  494. blob. This page reviews the most important cornerness measures as
  495. implemented in VLFeat:
  496. - @ref covdet-harris
  497. - @ref covdet-laplacian
  498. - @ref covdet-hessian
  499. This page makes use of notation introduced in @ref
  500. covdet-differential.
  501. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  502. @section covdet-harris Harris corners
  503. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  504. This section introduces the fist of the cornerness measure
  505. $\mathcal{F}[\ell]$. Recall (@ref covdet-cornerness) that the goal of
  506. this functional is to respond strongly to images $\ell$ of corner-like
  507. structure.
  508. Rather than explicitly encoding the appearance of corners, the idea of
  509. the Harris measure is to label as corner *any* image patch whose
  510. appearance is sufficiently distinctive to allow accurate
  511. localization. In particular, consider an image patch $\ell(\bx),
  512. \bx\in\Omega$, where $\Omega$ is a smooth circular window of radius
  513. approximately $\sigma_i$; at necessary condition for the patch to
  514. allow accurate localization is that even a small translation
  515. $\ell(\bx+\delta)$ causes the appearance to vary significantly (if not
  516. the origin and location $\delta$ would not be distinguishable from the
  517. image alone). This variation is measured by the sum of squared
  518. differences
  519. \[
  520. E(\delta) = \int g_{\sigma_i^2}(\bx)
  521. (\ell_{\sigma_d^2}(\bx+\delta) -
  522. \ell_{\sigma_d^2}(\bx))^2 \,d\bx
  523. \]
  524. Note that images are compared at scale $\sigma_d$, known as
  525. *differentiation scale* for reasons that will be clear in a moment,
  526. and that the squared differences are summed over a window softly
  527. defined by $\sigma_i$, also known as *integration scale*. This
  528. function can be approximated as $E(\delta)\approx \delta^\top
  529. M[\ell;\sigma_i^2,\sigma_d^2] \delta$ where
  530. \[
  531. M[\ell;\sigma_i^2,\sigma_d^2]
  532. = \int g_{\sigma_i^2}(\bx)
  533. (\nabla \ell_{\sigma_d^2}(\bx))
  534. (\nabla \ell_{\sigma_d^2}(\bx))^\top \, d\bx.
  535. \]
  536. is the so called **structure tensor**.
  537. A corner is identified when the sum of squared differences $E(\delta)$
  538. is large for displacements $\delta$ in all directions. This condition
  539. is obtained when both the eignenvalues $\lambda_1,\lambda_2$ of the
  540. structure tensor $M$ are large. The **Harris cornerness measure**
  541. captures this fact:
  542. \[
  543. \operatorname{Harris}[\ell;\sigma_i^2,\sigma_d^2] =
  544. \det M - \kappa \operatorname{trace}^2 M =
  545. \lambda_1\lambda_2 - \kappa (\lambda_1+\lambda_2)^2
  546. \]
  547. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  548. @subsection covdet-harris-warped Harris in the warped domain
  549. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  550. The cornerness measure of a feature a location $u$ (recall that
  551. locations $u$ are in general defined as image warps) should be
  552. computed after normalizing the image (by applying to it the warp
  553. $u^{-1}$). This section shows that, for affine warps, the Harris
  554. cornerness measure can be computed directly in the Gaussian affine
  555. scale space of the image. In particular, for similarities, it can be
  556. computed in the standard Gaussian scale space.
  557. To this end, let $u=(A,T)$ be an affine warp identifying a feature
  558. location in image $\ell(\bx)$. Let $\bar\ell(\bar\bx) =
  559. \ell(A\bar\bx+T)$ be the normalized image and rewrite the structure
  560. tensor of the normalized image as follows:
  561. \[
  562. M[\bar\ell; \bar\Sigma_i, \bar\Sigma_d]
  563. =
  564. M[\bar\ell; \bar\Sigma_i, \bar\Sigma_d](\mathbf{0})
  565. =
  566. \left[
  567. g_{\bar\Sigma_i} *
  568. (\nabla\bar\ell_{\bar\Sigma_d})
  569. (\nabla\bar\ell_{\bar\Sigma_d})^\top
  570. \right](\mathbf{0})
  571. \]
  572. This notation emphasizes that the structure tensor is obtained by
  573. taking derivatives and convolutions of the image. Using the fact that
  574. $\nabla g_{\bar\Sigma_d} * \bar\ell = A^\top (\nabla g_{A\bar\Sigma
  575. A^\top} * \ell) \circ (A,T)$ and that $g_{\bar\Sigma} * \bar \ell =
  576. (g_{A\bar\Sigma A^\top} * \ell) \circ (A,T)$, we get the equivalent
  577. expression:
  578. \[
  579. M[\bar\ell; \bar\Sigma_i, \bar\Sigma_d](\mathbf{0})
  580. =
  581. A^\top
  582. \left[
  583. g_{A\bar\Sigma_i A^\top} *
  584. (\nabla\ell_{A\bar\Sigma_dA^\top})(\nabla\ell_{A\bar\Sigma_d A^\top})^\top
  585. \right](A\mathbf{0}+T)
  586. A.
  587. \]
  588. In other words, the structure tensor of the normalized image can be
  589. computed as:
  590. \[
  591. M[\bar\ell; \bar\Sigma_i, \bar\Sigma_d](\mathbf{0})
  592. =
  593. A^\top M[\ell; \Sigma_i, \Sigma_d](T) A,
  594. \quad
  595. \Sigma_{i} = A\bar\Sigma_{i}A^\top,
  596. \quad
  597. \Sigma_{d} = A\bar\Sigma_{d}A^\top.
  598. \]
  599. This equation allows to compute the structure tensor for feature at
  600. all locations directly in the original image. In particular, features
  601. at all translations $T$ can be evaluated efficiently by computing
  602. convolutions and derivatives of the image
  603. $\ell_{A\bar\Sigma_dA^\top}$.
  604. A case of particular instance is when $\bar\Sigma_i= \bar\sigma_i^2 I$
  605. and $\bar\Sigma_d = \bar\sigma_d^2$ are both isotropic covariance
  606. matrices and the affine transformation is a similarity $A=sR$. Using
  607. the fact that $\det\left( s^2 R^\top M R \right)= s^4 \det M$ and
  608. $\operatorname{tr}\left(s^2 R^\top M R\right) = s^2 \operatorname{tr}
  609. M$, one obtains the relation
  610. \[
  611. \operatorname{Harris}[\bar \ell;\bar\sigma_i^2,\bar\sigma_d^2] =
  612. s^4 \operatorname{Harris}[\ell;s^2\bar\sigma_i^2,s^2\bar\sigma_d^2](T).
  613. \]
  614. This equation indicates that, for similarity transformations, not only
  615. the structure tensor, but directly the Harris cornerness measure can
  616. be computed on the original image and then be transferred back to the
  617. normalized domain. Note, however, that this requires rescaling the
  618. measure by the factor $s^4$.
  619. Another important consequence of this relation is that the Harris
  620. measure is invariant to pure image rotations. It cannot, therefore, be
  621. used to associate an orientation to the detected features.
  622. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  623. @section covdet-hessian Hessian blobs
  624. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  625. The *(determinant of the) Hessian* cornerness measure is given
  626. determinant of the Hessian of the image:
  627. \[
  628. \operatorname{DetHess}[\ell;\sigma_d^2]
  629. =
  630. \det H_{g_{\sigma_d^2} * \ell}(\mathbf{0})
  631. \]
  632. This number is large and positive if the image is locally curved
  633. (peaked), roughly corresponding to blob-like structures in the image.
  634. In particular, a large score requires the product of the eigenvalues
  635. of the Hessian to be large, which requires both of them to have the
  636. same sign and are large in absolute value.
  637. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  638. @subsection covdet-hessian-warped Hessian in the warped domain
  639. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  640. Similarly to the Harris measure, it is possible to work with the
  641. Hessian measure on the original unnormalized image. As before, let
  642. $\bar\ell(\bar\bx) = \ell(A\bar\bx+T)$ be the normalized image and
  643. rewrite the Hessian of the normalized image as follows:
  644. \[
  645. H_{g_{\bar\Sigma_d} * \bar\ell}(\mathbf{0}) = A^\top \left(H_{g_{\Sigma_d} * \ell}(T)\right) A.
  646. \]
  647. Then
  648. \[
  649. \operatorname{DetHess}[\bar\ell;\bar\Sigma_d]
  650. =
  651. (\det A)^2 \operatorname{DetHess}[\ell;A\bar\Sigma_d A^\top](T).
  652. \]
  653. In particular, for isotropic covariance matrices and similarity
  654. transformations $A=sR$:
  655. \[
  656. \operatorname{DetHess}[\bar\ell;\bar\sigma_d^2]
  657. =
  658. s^4 \operatorname{DetHess}[\ell;s^2\bar\sigma_d^2](T)
  659. \]
  660. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  661. @section covdet-laplacian Laplacian and Difference of Gaussians blobs
  662. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  663. The **Laplacian of Gaussian (LoG)** or **trace of the Hessian**
  664. cornerness measure is given by the trace of the Hessian of the image:
  665. \[
  666. \operatorname{Lap}[\ell;\sigma_d^2]
  667. =
  668. \operatorname{tr} H_{g_{\sigma_d}^2 * \ell}
  669. \]
  670. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  671. @subsection covdet-laplacian-warped Laplacian in the warped domain
  672. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  673. Similarly to the Hessian measure, the Laplacian cornenress can often
  674. be efficiently computed for features at all locations in the original
  675. unnormalized image domain. In particular, if the derivative covariance
  676. matrix $\Sigma_d$ is isotropic and one considers as warpings
  677. similarity transformations $A=sR$, where $R$ is a rotatin and $s$ a
  678. rescaling, one has
  679. \[
  680. \operatorname{Lap}[\bar\ell;\bar\sigma_d^2]
  681. =
  682. s^2 \operatorname{Lap}[\ell;s^2\bar\sigma_d^2](T)
  683. \]
  684. Note that, comparing to the Harris and determinant of Hessian
  685. measures, the scaling for the Laplacian is $s^2$ rather than $s^4$.
  686. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  687. @subsection covdet-laplacian-matched Laplacian as a matched filter
  688. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  689. The Laplacian is given by the trace of the Hessian
  690. operator. Differently from the determinant of the Hessian, this is a
  691. linear operation. This means that computing the Laplacian cornerness
  692. measure can be seen as applying a linear filtering operator to the
  693. image. This filter can then be interpreted as a *template* of a corner
  694. being matched to the image. Hence, the Laplacian cornerness measure
  695. can be interpreted as matching this corner template at all possible
  696. image locations.
  697. To see this formally, compute the Laplacian score in the input image domain:
  698. \[
  699. \operatorname{Lap}[\bar\ell;\bar\sigma_d^2]
  700. =
  701. s^2 \operatorname{Lap}[\ell;s^2\bar\sigma_d^2](T)
  702. =
  703. s^2 (\Delta g_{s^2\bar\sigma_d^2} * \ell)(T)
  704. \]
  705. The Laplacian fitler is obtained by moving the Laplacian operator from
  706. the image to the Gaussian smoothing kernel:
  707. \[
  708. s^2 (\Delta g_{s^2\bar\sigma_d^2} * \ell)
  709. =
  710. (s^2 \Delta g_{s^2\bar\sigma_d^2}) * \ell
  711. \]
  712. Note that the filter is rescaled by the $s^2$; sometimes, this factor
  713. is incorporated in the Laplacian operator, yielding the so-called
  714. normalized Laplacian.
  715. The Laplacian of Gaussian is also called *top-hat function* and has
  716. the expression:
  717. \[
  718. \Delta g_{\sigma^2}(x,y)
  719. =
  720. \frac{x^2+y^2 - 2 \sigma^2}{\sigma^4} g_{\sigma^2}(x,y).
  721. \]
  722. This filter, which acts as corner template, resembles a blob (a dark
  723. disk surrounded by a bright ring).
  724. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  725. @subsection covdet-laplacian-dog Difference of Gaussians
  726. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  727. The **Difference of Gaussian** (DoG) cornerness measure can be
  728. interpreted as an approximation of the Laplacian that is easy to
  729. obtain once a scalespace of the input image has been computed.
  730. As noted above, the Laplacian cornerness of the normalized feature can
  731. be computed directly from the input image by convolving the image by
  732. the normalized Laplacian of Gaussian filter $s^2 \Delta
  733. g_{s^2\bar\sigma_d^2}$.
  734. Like the other derivative operators, this filter is simpe to
  735. discriteize. However, it is often approximated by computing the the
  736. *Difference of Gaussians* (DoG) approximation instead. This
  737. approximation is obtained from the easily-proved identity:
  738. \[
  739. \frac{\partial}{\partial \sigma} g_{\sigma^2} =
  740. \sigma \Delta g_{\sigma^2}.
  741. \]
  742. This indicates that computing the normalized Laplacian of a Gaussian
  743. filter is, in the limit, the same as taking the difference between
  744. Gaussian filters of slightly increasing standard deviation $\sigma$
  745. and $\kappa\sigma$, where $\kappa \approx 1$:
  746. \[
  747. \sigma^2 \Delta g_{\sigma^2}
  748. \approx
  749. \sigma \frac{g_{(\kappa\sigma)^2} - g_{\sigma^2}}{\kappa\sigma - \sigma}
  750. =
  751. \frac{1}{\kappa - 1}
  752. (g_{(\kappa\sigma)^2} - g_{\sigma^2}).
  753. \]
  754. One nice propery of this expression is that the factor $\sigma$
  755. cancels out in the right-hand side. Usually, scales $\sigma$ and
  756. $\kappa\sigma$ are pre-computed in the image scale-space and
  757. successive scales are sampled with uniform geometric spacing, meaning
  758. that the factor $\kappa$ is the same for all scales. Then, up to a
  759. overall scaling factor, the LoG cornerness measure can be obtained by
  760. taking the difference of successive scale space images
  761. $\ell_{(\kappa\sigma)^2}$ and $\ell_{\sigma^2}$.
  762. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  763. @page covdet-affine-adaptation Affine adaptation
  764. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  765. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  766. @page covdet-dominant-orientation Dominant orientation
  767. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  768. **/
  769. #include "covdet.h"
  770. #include <string.h>
  771. /** @brief Reallocate buffer
  772. ** @param buffer
  773. ** @param bufferSize
  774. ** @param targetSize
  775. ** @return error code
  776. **/
  777. static int
  778. _vl_resize_buffer (void ** buffer, vl_size * bufferSize, vl_size targetSize) {
  779. void * newBuffer ;
  780. if (*buffer == NULL) {
  781. *buffer = vl_malloc(targetSize) ;
  782. if (*buffer) {
  783. *bufferSize = targetSize ;
  784. return VL_ERR_OK ;
  785. } else {
  786. *bufferSize = 0 ;
  787. return VL_ERR_ALLOC ;
  788. }
  789. }
  790. newBuffer = vl_realloc(*buffer, targetSize) ;
  791. if (newBuffer) {
  792. *buffer = newBuffer ;
  793. *bufferSize = targetSize ;
  794. return VL_ERR_OK ;
  795. } else {
  796. return VL_ERR_ALLOC ;
  797. }
  798. }
  799. /** @brief Enlarge buffer
  800. ** @param buffer
  801. ** @param bufferSize
  802. ** @param targetSize
  803. ** @return error code
  804. **/
  805. static int
  806. _vl_enlarge_buffer (void ** buffer, vl_size * bufferSize, vl_size targetSize) {
  807. if (*bufferSize >= targetSize) return VL_ERR_OK ;
  808. return _vl_resize_buffer(buffer,bufferSize,targetSize) ;
  809. }
  810. /* ---------------------------------------------------------------- */
  811. /* Finding local extrema */
  812. /* ---------------------------------------------------------------- */
  813. /* Todo: make this generally available in the library */
  814. typedef struct _VlCovDetExtremum2
  815. {
  816. vl_index xi ;
  817. vl_index yi ;
  818. float x ;
  819. float y ;
  820. float peakScore ;
  821. float edgeScore ;
  822. } VlCovDetExtremum2 ;
  823. typedef struct _VlCovDetExtremum3
  824. {
  825. vl_index xi ;
  826. vl_index yi ;
  827. vl_index zi ;
  828. float x ;
  829. float y ;
  830. float z ;
  831. float peakScore ;
  832. float edgeScore ;
  833. } VlCovDetExtremum3 ;
  834. VL_EXPORT vl_size
  835. vl_find_local_extrema_3 (vl_index ** extrema, vl_size * bufferSize,
  836. float const * map,
  837. vl_size width, vl_size height, vl_size depth,
  838. double threshold) ;
  839. VL_EXPORT vl_size
  840. vl_find_local_extrema_2 (vl_index ** extrema, vl_size * bufferSize,
  841. float const * map,
  842. vl_size width, vl_size height,
  843. double threshold) ;
  844. VL_EXPORT vl_bool
  845. vl_refine_local_extreum_3 (VlCovDetExtremum3 * refined,
  846. float const * map,
  847. vl_size width, vl_size height, vl_size depth,
  848. vl_index x, vl_index y, vl_index z) ;
  849. VL_EXPORT vl_bool
  850. vl_refine_local_extreum_2 (VlCovDetExtremum2 * refined,
  851. float const * map,
  852. vl_size width, vl_size height,
  853. vl_index x, vl_index y) ;
  854. /** @internal
  855. ** @brief Find the extrema of a 3D function
  856. ** @param extrema buffer containing the extrema found (in/out).
  857. ** @param bufferSize size of the @a extrema buffer in bytes (in/out).
  858. ** @param map a 3D array representing the map.
  859. ** @param width of the map.
  860. ** @param height of the map.
  861. ** @param depth of the map.
  862. ** @param threshold minumum extremum value.
  863. ** @return number of extrema found.
  864. ** @see @ref ::vl_refine_local_extreum_2.
  865. **/
  866. vl_size
  867. vl_find_local_extrema_3 (vl_index ** extrema, vl_size * bufferSize,
  868. float const * map,
  869. vl_size width, vl_size height, vl_size depth,
  870. double threshold)
  871. {
  872. vl_index x, y, z ;
  873. vl_size const xo = 1 ;
  874. vl_size const yo = width ;
  875. vl_size const zo = width * height ;
  876. float const *pt = map + xo + yo + zo ;
  877. vl_size numExtrema = 0 ;
  878. vl_size requiredSize = 0 ;
  879. #define CHECK_NEIGHBORS_3(v,CMP,SGN) (\
  880. v CMP ## = SGN threshold && \
  881. v CMP *(pt + xo) && \
  882. v CMP *(pt - xo) && \
  883. v CMP *(pt + zo) && \
  884. v CMP *(pt - zo) && \
  885. v CMP *(pt + yo) && \
  886. v CMP *(pt - yo) && \
  887. \
  888. v CMP *(pt + yo + xo) && \
  889. v CMP *(pt + yo - xo) && \
  890. v CMP *(pt - yo + xo) && \
  891. v CMP *(pt - yo - xo) && \
  892. \
  893. v CMP *(pt + xo + zo) && \
  894. v CMP *(pt - xo + zo) && \
  895. v CMP *(pt + yo + zo) && \
  896. v CMP *(pt - yo + zo) && \
  897. v CMP *(pt + yo + xo + zo) && \
  898. v CMP *(pt + yo - xo + zo) && \
  899. v CMP *(pt - yo + xo + zo) && \
  900. v CMP *(pt - yo - xo + zo) && \
  901. \
  902. v CMP *(pt + xo - zo) && \
  903. v CMP *(pt - xo - zo) && \
  904. v CMP *(pt + yo - zo) && \
  905. v CMP *(pt - yo - zo) && \
  906. v CMP *(pt + yo + xo - zo) && \
  907. v CMP *(pt + yo - xo - zo) && \
  908. v CMP *(pt - yo + xo - zo) && \
  909. v CMP *(pt - yo - xo - zo) )
  910. for (z = 1 ; z < (signed)depth - 1 ; ++z) {
  911. for (y = 1 ; y < (signed)height - 1 ; ++y) {
  912. for (x = 1 ; x < (signed)width - 1 ; ++x) {
  913. float value = *pt ;
  914. if (CHECK_NEIGHBORS_3(value,>,+) || CHECK_NEIGHBORS_3(value,<,-)) {
  915. numExtrema ++ ;
  916. requiredSize += sizeof(vl_index) * 3 ;
  917. if (*bufferSize < requiredSize) {
  918. int err = _vl_resize_buffer((void**)extrema, bufferSize,
  919. requiredSize + 2000 * 3 * sizeof(vl_index)) ;
  920. if (err != VL_ERR_OK) abort() ;
  921. }
  922. (*extrema) [3 * (numExtrema - 1) + 0] = x ;
  923. (*extrema) [3 * (numExtrema - 1) + 1] = y ;
  924. (*extrema) [3 * (numExtrema - 1) + 2] = z ;
  925. }
  926. pt += xo ;
  927. }
  928. pt += 2*xo ;
  929. }
  930. pt += 2*yo ;
  931. }
  932. return numExtrema ;
  933. }
  934. /** @internal
  935. ** @brief Find extrema in a 2D function
  936. ** @param extrema buffer containing the found extrema (in/out).
  937. ** @param bufferSize size of the @a extrema buffer in bytes (in/out).
  938. ** @param map a 3D array representing the map.
  939. ** @param width of the map.
  940. ** @param height of the map.
  941. ** @param threshold minumum extremum value.
  942. ** @return number of extrema found.
  943. **
  944. ** An extremum contains 2 ::vl_index values; they are arranged
  945. ** sequentially.
  946. **
  947. ** The function can reuse an already allocated buffer if
  948. ** @a extrema and @a bufferSize are initialized on input.
  949. ** It may have to @a realloc the memory if the buffer is too small.
  950. **/
  951. vl_size
  952. vl_find_local_extrema_2 (vl_index ** extrema, vl_size * bufferSize,
  953. float const* map,
  954. vl_size width, vl_size height,
  955. double threshold)
  956. {
  957. vl_index x, y ;
  958. vl_size const xo = 1 ;
  959. vl_size const yo = width ;
  960. float const *pt = map + xo + yo ;
  961. vl_size numExtrema = 0 ;
  962. vl_size requiredSize = 0 ;
  963. #define CHECK_NEIGHBORS_2(v,CMP,SGN) (\
  964. v CMP ## = SGN threshold && \
  965. v CMP *(pt + xo) && \
  966. v CMP *(pt - xo) && \
  967. v CMP *(pt + yo) && \
  968. v CMP *(pt - yo) && \
  969. \
  970. v CMP *(pt + yo + xo) && \
  971. v CMP *(pt + yo - xo) && \
  972. v CMP *(pt - yo + xo) && \
  973. v CMP *(pt - yo - xo) )
  974. for (y = 1 ; y < (signed)height - 1 ; ++y) {
  975. for (x = 1 ; x < (signed)width - 1 ; ++x) {
  976. float value = *pt ;
  977. if (CHECK_NEIGHBORS_2(value,>,+) || CHECK_NEIGHBORS_2(value,<,-)) {
  978. numExtrema ++ ;
  979. requiredSize += sizeof(vl_index) * 2 ;
  980. if (*bufferSize < requiredSize) {
  981. int err = _vl_resize_buffer((void**)extrema, bufferSize,
  982. requiredSize + 2000 * 2 * sizeof(vl_index)) ;
  983. if (err != VL_ERR_OK) abort() ;
  984. }
  985. (*extrema) [2 * (numExtrema - 1) + 0] = x ;
  986. (*extrema) [2 * (numExtrema - 1) + 1] = y ;
  987. }
  988. pt += xo ;
  989. }
  990. pt += 2*xo ;
  991. }
  992. return numExtrema ;
  993. }
  994. /** @internal
  995. ** @brief Refine the location of a local extremum of a 3D map
  996. ** @param refined refined extremum (out).
  997. ** @param map a 3D array representing the map.
  998. ** @param width of the map.
  999. ** @param height of the map.
  1000. ** @param depth of the map.
  1001. ** @param x initial x position.
  1002. ** @param y initial y position.
  1003. ** @param z initial z position.
  1004. ** @return a flat indicating whether the extrema refinement was stable.
  1005. **/
  1006. VL_EXPORT vl_bool
  1007. vl_refine_local_extreum_3 (VlCovDetExtremum3 * refined,
  1008. float const * map,
  1009. vl_size width, vl_size height, vl_size depth,
  1010. vl_index x, vl_index y, vl_index z)
  1011. {
  1012. vl_size const xo = 1 ;
  1013. vl_size const yo = width ;
  1014. vl_size const zo = width * height ;
  1015. double Dx=0,Dy=0,Dz=0,Dxx=0,Dyy=0,Dzz=0,Dxy=0,Dxz=0,Dyz=0 ;
  1016. double A [3*3], b [3] ;
  1017. #define at(dx,dy,dz) (*(pt + (dx)*xo + (dy)*yo + (dz)*zo))
  1018. #define Aat(i,j) (A[(i)+(j)*3])
  1019. float const * pt ;
  1020. vl_index dx = 0 ;
  1021. vl_index dy = 0 ;
  1022. /*vl_index dz = 0 ;*/
  1023. vl_index iter ;
  1024. int err ;
  1025. assert (map) ;
  1026. assert (1 <= x && x <= (signed)width - 2) ;
  1027. assert (1 <= y && y <= (signed)height - 2) ;
  1028. assert (1 <= z && z <= (signed)depth - 2) ;
  1029. for (iter = 0 ; iter < 5 ; ++iter) {
  1030. x += dx ;
  1031. y += dy ;
  1032. pt = map + x*xo + y*yo + z*zo ;
  1033. /* compute the gradient */
  1034. Dx = 0.5 * (at(+1,0,0) - at(-1,0,0)) ;
  1035. Dy = 0.5 * (at(0,+1,0) - at(0,-1,0));
  1036. Dz = 0.5 * (at(0,0,+1) - at(0,0,-1)) ;
  1037. /* compute the Hessian */
  1038. Dxx = (at(+1,0,0) + at(-1,0,0) - 2.0 * at(0,0,0)) ;
  1039. Dyy = (at(0,+1,0) + at(0,-1,0) - 2.0 * at(0,0,0)) ;
  1040. Dzz = (at(0,0,+1) + at(0,0,-1) - 2.0 * at(0,0,0)) ;
  1041. Dxy = 0.25 * (at(+1,+1,0) + at(-1,-1,0) - at(-1,+1,0) - at(+1,-1,0)) ;
  1042. Dxz = 0.25 * (at(+1,0,+1) + at(-1,0,-1) - at(-1,0,+1) - at(+1,0,-1)) ;
  1043. Dyz = 0.25 * (at(0,+1,+1) + at(0,-1,-1) - at(0,-1,+1) - at(0,+1,-1)) ;
  1044. /* solve linear system */
  1045. Aat(0,0) = Dxx ;
  1046. Aat(1,1) = Dyy ;
  1047. Aat(2,2) = Dzz ;
  1048. Aat(0,1) = Aat(1,0) = Dxy ;
  1049. Aat(0,2) = Aat(2,0) = Dxz ;
  1050. Aat(1,2) = Aat(2,1) = Dyz ;
  1051. b[0] = - Dx ;
  1052. b[1] = - Dy ;
  1053. b[2] = - Dz ;
  1054. err = vl_solve_linear_system_3(b, A, b) ;
  1055. if (err != VL_ERR_OK) {
  1056. b[0] = 0 ;
  1057. b[1] = 0 ;
  1058. b[2] = 0 ;
  1059. break ;
  1060. }
  1061. /* Keep going if there is sufficient translation */
  1062. dx = (b[0] > 0.6 && x < (signed)width - 2 ? 1 : 0)
  1063. + (b[0] < -0.6 && x > 1 ? -1 : 0) ;
  1064. dy = (b[1] > 0.6 && y < (signed)height - 2 ? 1 : 0)
  1065. + (b[1] < -0.6 && y > 1 ? -1 : 0) ;
  1066. if (dx == 0 && dy == 0) break ;
  1067. }
  1068. /* check threshold and other conditions */
  1069. {
  1070. double peakScore = at(0,0,0)
  1071. + 0.5 * (Dx * b[0] + Dy * b[1] + Dz * b[2]) ;
  1072. double alpha = (Dxx+Dyy)*(Dxx+Dyy) / (Dxx*Dyy - Dxy*Dxy) ;
  1073. double edgeScore ;
  1074. if (alpha < 0) {
  1075. /* not an extremum */
  1076. edgeScore = VL_INFINITY_D ;
  1077. } else {
  1078. edgeScore = (0.5*alpha - 1) + sqrt(VL_MAX(0.25*alpha - 1,0)*alpha) ;
  1079. }
  1080. refined->xi = x ;
  1081. refined->yi = y ;
  1082. refined->zi = z ;
  1083. refined->x = x + b[0] ;
  1084. refined->y = y + b[1] ;
  1085. refined->z = z + b[2] ;
  1086. refined->peakScore = peakScore ;
  1087. refined->edgeScore = edgeScore ;
  1088. return
  1089. err == VL_ERR_OK &&
  1090. vl_abs_d(b[0]) < 1.5 &&
  1091. vl_abs_d(b[1]) < 1.5 &&
  1092. vl_abs_d(b[2]) < 1.5 &&
  1093. 0 <= refined->x && refined->x <= (signed)width - 1 &&
  1094. 0 <= refined->y && refined->y <= (signed)height - 1 &&
  1095. 0 <= refined->z && refined->z <= (signed)depth - 1 ;
  1096. }
  1097. #undef Aat
  1098. #undef at
  1099. }
  1100. /** @internal
  1101. ** @brief Refine the location of a local extremum of a 2D map
  1102. ** @param refined refined extremum (out).
  1103. ** @param map a 2D array representing the map.
  1104. ** @param width of the map.
  1105. ** @param height of the map.
  1106. ** @param x initial x position.
  1107. ** @param y initial y position.
  1108. ** @return a flat indicating whether the extrema refinement was stable.
  1109. **/
  1110. VL_EXPORT vl_bool
  1111. vl_refine_local_extreum_2 (VlCovDetExtremum2 * refined,
  1112. float const * map,
  1113. vl_size width, vl_size height,
  1114. vl_index x, vl_index y)
  1115. {
  1116. vl_size const xo = 1 ;
  1117. vl_size const yo = width ;
  1118. double Dx=0,Dy=0,Dxx=0,Dyy=0,Dxy=0;
  1119. double A [2*2], b [2] ;
  1120. #define at(dx,dy) (*(pt + (dx)*xo + (dy)*yo ))
  1121. #define Aat(i,j) (A[(i)+(j)*2])
  1122. float const * pt ;
  1123. vl_index dx = 0 ;
  1124. vl_index dy = 0 ;
  1125. vl_index iter ;
  1126. int err ;
  1127. assert (map) ;
  1128. assert (1 <= x && x <= (signed)width - 2) ;
  1129. assert (1 <= y && y <= (signed)height - 2) ;
  1130. for (iter = 0 ; iter < 5 ; ++iter) {
  1131. x += dx ;
  1132. y += dy ;
  1133. pt = map + x*xo + y*yo ;
  1134. /* compute the gradient */
  1135. Dx = 0.5 * (at(+1,0) - at(-1,0)) ;
  1136. Dy = 0.5 * (at(0,+1) - at(0,-1));
  1137. /* compute the Hessian */
  1138. Dxx = (at(+1,0) + at(-1,0) - 2.0 * at(0,0)) ;
  1139. Dyy = (at(0,+1) + at(0,-1) - 2.0 * at(0,0)) ;
  1140. Dxy = 0.25 * (at(+1,+1) + at(-1,-1) - at(-1,+1) - at(+1,-1)) ;
  1141. /* solve linear system */
  1142. Aat(0,0) = Dxx ;
  1143. Aat(1,1) = Dyy ;
  1144. Aat(0,1) = Aat(1,0) = Dxy ;
  1145. b[0] = - Dx ;
  1146. b[1] = - Dy ;
  1147. err = vl_solve_linear_system_2(b, A, b) ;
  1148. if (err != VL_ERR_OK) {
  1149. b[0] = 0 ;
  1150. b[1] = 0 ;
  1151. break ;
  1152. }
  1153. /* Keep going if there is sufficient translation */
  1154. dx = (b[0] > 0.6 && x < (signed)width - 2 ? 1 : 0)
  1155. + (b[0] < -0.6 && x > 1 ? -1 : 0) ;
  1156. dy = (b[1] > 0.6 && y < (signed)height - 2 ? 1 : 0)
  1157. + (b[1] < -0.6 && y > 1 ? -1 : 0) ;
  1158. if (dx == 0 && dy == 0) break ;
  1159. }
  1160. /* check threshold and other conditions */
  1161. {
  1162. double peakScore = at(0,0) + 0.5 * (Dx * b[0] + Dy * b[1]) ;
  1163. double alpha = (Dxx+Dyy)*(Dxx+Dyy) / (Dxx*Dyy - Dxy*Dxy) ;
  1164. double edgeScore ;
  1165. if (alpha < 0) {
  1166. /* not an extremum */
  1167. edgeScore = VL_INFINITY_D ;
  1168. } else {
  1169. edgeScore = (0.5*alpha - 1) + sqrt(VL_MAX(0.25*alpha - 1,0)*alpha) ;
  1170. }
  1171. refined->xi = x ;
  1172. refined->yi = y ;
  1173. refined->x = x + b[0] ;
  1174. refined->y = y + b[1] ;
  1175. refined->peakScore = peakScore ;
  1176. refined->edgeScore = edgeScore ;
  1177. return
  1178. err == VL_ERR_OK &&
  1179. vl_abs_d(b[0]) < 1.5 &&
  1180. vl_abs_d(b[1]) < 1.5 &&
  1181. 0 <= refined->x && refined->x <= (signed)width - 1 &&
  1182. 0 <= refined->y && refined->y <= (signed)height - 1 ;
  1183. }
  1184. #undef Aat
  1185. #undef at
  1186. }
  1187. /* ---------------------------------------------------------------- */
  1188. /* Covarant detector */
  1189. /* ---------------------------------------------------------------- */
  1190. #define VL_COVDET_MAX_NUM_ORIENTATIONS 4
  1191. #define VL_COVDET_MAX_NUM_LAPLACIAN_SCALES 4
  1192. #define VL_COVDET_AA_PATCH_RESOLUTION 20
  1193. #define VL_COVDET_AA_MAX_NUM_ITERATIONS 15
  1194. #define VL_COVDET_OR_NUM_ORIENTATION_HISTOGAM_BINS 36
  1195. #define VL_COVDET_AA_RELATIVE_INTEGRATION_SIGMA 3
  1196. #define VL_COVDET_AA_RELATIVE_DERIVATIVE_SIGMA 1
  1197. #define VL_COVDET_AA_MAX_ANISOTROPY 5
  1198. #define VL_COVDET_AA_CONVERGENCE_THRESHOLD 1.001
  1199. #define VL_COVDET_AA_ACCURATE_SMOOTHING VL_FALSE
  1200. #define VL_COVDET_AA_PATCH_EXTENT (3*VL_COVDET_AA_RELATIVE_INTEGRATION_SIGMA)
  1201. #define VL_COVDET_OR_ADDITIONAL_PEAKS_RELATIVE_SIZE 0.8
  1202. #define VL_COVDET_LAP_NUM_LEVELS 10
  1203. #define VL_COVDET_LAP_PATCH_RESOLUTION 16
  1204. #define VL_COVDET_LAP_DEF_PEAK_THRESHOLD 0.01
  1205. #define VL_COVDET_DOG_DEF_PEAK_THRESHOLD VL_COVDET_LAP_DEF_PEAK_THRESHOLD
  1206. #define VL_COVDET_DOG_DEF_EDGE_THRESHOLD 10.0
  1207. #define VL_COVDET_HARRIS_DEF_PEAK_THRESHOLD 0.000002
  1208. #define VL_COVDET_HARRIS_DEF_EDGE_THRESHOLD 10.0
  1209. #define VL_COVDET_HESSIAN_DEF_PEAK_THRESHOLD 0.003
  1210. #define VL_COVDET_HESSIAN_DEF_EDGE_THRESHOLD 10.0
  1211. /** @brief Covariant feature detector */
  1212. struct _VlCovDet
  1213. {
  1214. VlScaleSpace *gss ; /**< Gaussian scale space. */
  1215. VlScaleSpace *css ; /**< Cornerness scale space. */
  1216. VlCovDetMethod method ; /**< feature extraction method. */
  1217. double peakThreshold ; /**< peak threshold. */
  1218. double edgeThreshold ; /**< edge threshold. */
  1219. double lapPeakThreshold; /**< peak threshold for Laplacian scale selection. */
  1220. vl_size octaveResolution ; /**< resolution of each octave. */
  1221. vl_index firstOctave ; /**< index of the first octave. */
  1222. double nonExtremaSuppression ;
  1223. vl_size numNonExtremaSuppressed ;
  1224. VlCovDetFeature *features ;
  1225. vl_size numFeatures ;
  1226. vl_size numFeatureBufferSize ;
  1227. float * patch ;
  1228. vl_size patchBufferSize ;
  1229. vl_bool transposed ;
  1230. VlCovDetFeatureOrientation orientations [VL_COVDET_MAX_NUM_ORIENTATIONS] ;
  1231. VlCovDetFeatureLaplacianScale scales [VL_COVDET_MAX_NUM_LAPLACIAN_SCALES] ;
  1232. vl_bool aaAccurateSmoothing ;
  1233. float aaPatch [(2*VL_COVDET_AA_PATCH_RESOLUTION+1)*(2*VL_COVDET_AA_PATCH_RESOLUTION+1)] ;
  1234. float aaPatchX [(2*VL_COVDET_AA_PATCH_RESOLUTION+1)*(2*VL_COVDET_AA_PATCH_RESOLUTION+1)] ;
  1235. float aaPatchY [(2*VL_COVDET_AA_PATCH_RESOLUTION+1)*(2*VL_COVDET_AA_PATCH_RESOLUTION+1)] ;
  1236. float aaMask [(2*VL_COVDET_AA_PATCH_RESOLUTION+1)*(2*VL_COVDET_AA_PATCH_RESOLUTION+1)] ;
  1237. float lapPatch [(2*VL_COVDET_LAP_PATCH_RESOLUTION+1)*(2*VL_COVDET_LAP_PATCH_RESOLUTION+1)] ;
  1238. float laplacians [(2*VL_COVDET_LAP_PATCH_RESOLUTION+1)*(2*VL_COVDET_LAP_PATCH_RESOLUTION+1)*VL_COVDET_LAP_NUM_LEVELS] ;
  1239. vl_size numFeaturesWithNumScales [VL_COVDET_MAX_NUM_LAPLACIAN_SCALES + 1] ;
  1240. } ;
  1241. VlEnumerator vlCovdetMethods [VL_COVDET_METHOD_NUM] = {
  1242. {"DoG" , (vl_index)VL_COVDET_METHOD_DOG },
  1243. {"Hessian", (vl_index)VL_COVDET_METHOD_HESSIAN },
  1244. {"HessianLaplace", (vl_index)VL_COVDET_METHOD_HESSIAN_LAPLACE },
  1245. {"HarrisLaplace", (vl_index)VL_COVDET_METHOD_HARRIS_LAPLACE },
  1246. {"MultiscaleHessian", (vl_index)VL_COVDET_METHOD_MULTISCALE_HESSIAN},
  1247. {"MultiscaleHarris", (vl_index)VL_COVDET_METHOD_MULTISCALE_HARRIS },
  1248. {0, 0 }
  1249. } ;
  1250. /** @brief Create a new object instance
  1251. ** @param method method for covariant feature detection.
  1252. ** @return new covariant detector.
  1253. **/
  1254. VlCovDet *
  1255. vl_covdet_new (VlCovDetMethod method)
  1256. {
  1257. VlCovDet * self =(VlCovDet*)vl_calloc(sizeof(VlCovDet),1) ;
  1258. self->method = method ;
  1259. self->octaveResolution = 3 ;
  1260. self->firstOctave = -1 ;
  1261. switch (self->method) {
  1262. case VL_COVDET_METHOD_DOG :
  1263. self->peakThreshold = VL_COVDET_DOG_DEF_PEAK_THRESHOLD ;
  1264. self->edgeThreshold = VL_COVDET_DOG_DEF_EDGE_THRESHOLD ;
  1265. self->lapPeakThreshold = 0 ; /* not used */
  1266. break ;
  1267. case VL_COVDET_METHOD_HARRIS_LAPLACE:
  1268. case VL_COVDET_METHOD_MULTISCALE_HARRIS:
  1269. self->peakThreshold = VL_COVDET_HARRIS_DEF_PEAK_THRESHOLD ;
  1270. self->edgeThreshold = VL_COVDET_HARRIS_DEF_EDGE_THRESHOLD ;
  1271. self->lapPeakThreshold = VL_COVDET_LAP_DEF_PEAK_THRESHOLD ;
  1272. break ;
  1273. case VL_COVDET_METHOD_HESSIAN :
  1274. case VL_COVDET_METHOD_HESSIAN_LAPLACE:
  1275. case VL_COVDET_METHOD_MULTISCALE_HESSIAN:
  1276. self->peakThreshold = VL_COVDET_HESSIAN_DEF_PEAK_THRESHOLD ;
  1277. self->edgeThreshold = VL_COVDET_HESSIAN_DEF_EDGE_THRESHOLD ;
  1278. self->lapPeakThreshold = VL_COVDET_LAP_DEF_PEAK_THRESHOLD ;
  1279. break;
  1280. default:
  1281. assert(0) ;
  1282. }
  1283. self->nonExtremaSuppression = 0.5 ;
  1284. self->features = NULL ;
  1285. self->numFeatures = 0 ;
  1286. self->numFeatureBufferSize = 0 ;
  1287. self->patch = NULL ;
  1288. self->patchBufferSize = 0 ;
  1289. self->transposed = VL_FALSE ;
  1290. self->aaAccurateSmoothing = VL_COVDET_AA_ACCURATE_SMOOTHING ;
  1291. {
  1292. vl_index const w = VL_COVDET_AA_PATCH_RESOLUTION ;
  1293. vl_index i,j ;
  1294. double step = (2.0 * VL_COVDET_AA_PATCH_EXTENT) / (2*w+1) ;
  1295. double sigma = VL_COVDET_AA_RELATIVE_INTEGRATION_SIGMA ;
  1296. for (j = -w ; j <= w ; ++j) {
  1297. for (i = -w ; i <= w ; ++i) {
  1298. double dx = i*step/sigma ;
  1299. double dy = j*step/sigma ;
  1300. self->aaMask[(i+w) + (2*w+1)*(j+w)] = exp(-0.5*(dx*dx+dy*dy)) ;
  1301. }
  1302. }
  1303. }
  1304. {
  1305. /*
  1306. Covers one octave of Laplacian filters, from sigma=1 to sigma=2.
  1307. The spatial sampling step is 0.5.
  1308. */
  1309. vl_index s ;
  1310. for (s = 0 ; s < VL_COVDET_LAP_NUM_LEVELS ; ++s) {
  1311. double sigmaLap = pow(2.0, -0.5 +
  1312. (double)s / (VL_COVDET_LAP_NUM_LEVELS - 1)) ;
  1313. double const sigmaImage = 1.0 / sqrt(2.0) ;
  1314. double const step = 0.5 * sigmaImage ;
  1315. double const sigmaDelta = sqrt(sigmaLap*sigmaLap - sigmaImage*sigmaImage) ;
  1316. vl_size const w = VL_COVDET_LAP_PATCH_RESOLUTION ;
  1317. vl_size const num = 2 * w + 1 ;
  1318. float * pt = self->laplacians + s * (num * num) ;
  1319. memset(pt, 0, num * num * sizeof(float)) ;
  1320. #define at(x,y) pt[(x+w)+(y+w)*(2*w+1)]
  1321. at(0,0) = - 4.0 ;
  1322. at(-1,0) = 1.0 ;
  1323. at(+1,0) = 1.0 ;
  1324. at(0,1) = 1.0 ;
  1325. at(0,-1) = 1.0 ;
  1326. #undef at
  1327. vl_imsmooth_f(pt, num,
  1328. pt, num, num, num,
  1329. sigmaDelta / step, sigmaDelta / step) ;
  1330. #if 0
  1331. {
  1332. char name [200] ;
  1333. snprintf(name, 200, "/tmp/%f-lap.pgm", sigmaDelta) ;
  1334. vl_pgm_write_f(name, pt, num, num) ;
  1335. }
  1336. #endif
  1337. }
  1338. }
  1339. return self ;
  1340. }
  1341. /** @brief Reset object
  1342. ** @param self object.
  1343. **
  1344. ** This function removes any buffered features and frees other
  1345. ** internal buffers.
  1346. **/
  1347. void
  1348. vl_covdet_reset (VlCovDet * self)
  1349. {
  1350. if (self->features) {
  1351. vl_free(self->features) ;
  1352. self->features = NULL ;
  1353. }
  1354. if (self->css) {
  1355. vl_scalespace_delete(self->css) ;
  1356. self->css = NULL ;
  1357. }
  1358. if (self->gss) {
  1359. vl_scalespace_delete(self->gss) ;
  1360. self->gss = NULL ;
  1361. }
  1362. }
  1363. /** @brief Delete object instance
  1364. ** @param self object.
  1365. **/
  1366. void
  1367. vl_covdet_delete (VlCovDet * self)
  1368. {
  1369. vl_covdet_reset(self) ;
  1370. if (self->patch) vl_free (self->patch) ;
  1371. vl_free(self) ;
  1372. }
  1373. /** @brief Append a feature to the internal buffer.
  1374. ** @param self object.
  1375. ** @param feature a pointer to the feature to append.
  1376. ** @return status.
  1377. **
  1378. ** The feature is copied. The function may fail with @c status
  1379. ** equal to ::VL_ERR_ALLOC if there is insufficient memory.
  1380. **/
  1381. int
  1382. vl_covdet_append_feature (VlCovDet * self, VlCovDetFeature const * feature)
  1383. {
  1384. vl_size requiredSize ;
  1385. assert(self) ;
  1386. assert(feature) ;
  1387. self->numFeatures ++ ;
  1388. requiredSize = self->numFeatures * sizeof(VlCovDetFeature) ;
  1389. if (requiredSize > self->numFeatureBufferSize) {
  1390. int err = _vl_resize_buffer((void**)&self->features, &self->numFeatureBufferSize,
  1391. (self->numFeatures + 1000) * sizeof(VlCovDetFeature)) ;
  1392. if (err) {
  1393. self->numFeatures -- ;
  1394. return err ;
  1395. }
  1396. }
  1397. self->features[self->numFeatures - 1] = *feature ;
  1398. return VL_ERR_OK ;
  1399. }
  1400. /* ---------------------------------------------------------------- */
  1401. /* Process a new image */
  1402. /* ---------------------------------------------------------------- */
  1403. /** @brief Detect features in an image
  1404. ** @param self object.
  1405. ** @param image image to process.
  1406. ** @param width image width.
  1407. ** @param height image height.
  1408. ** @return status.
  1409. **
  1410. ** @a width and @a height must be at least one pixel. The function
  1411. ** fails by returing ::VL_ERR_ALLOC if the memory is insufficient.
  1412. **/
  1413. int
  1414. vl_covdet_put_image (VlCovDet * self,
  1415. float const * image,
  1416. vl_size width, vl_size height)
  1417. {
  1418. vl_size const minOctaveSize = 16 ;
  1419. vl_index lastOctave ;
  1420. vl_index octaveFirstSubdivision ;
  1421. vl_index octaveLastSubdivision ;
  1422. VlScaleSpaceGeometry geom = vl_scalespace_get_default_geometry(width,height) ;
  1423. assert (self) ;
  1424. assert (image) ;
  1425. assert (width >= 1) ;
  1426. assert (height >= 1) ;
  1427. /* (minOctaveSize - 1) 2^lastOctave <= min(width,height) - 1 */
  1428. lastOctave = vl_floor_d(vl_log2_d(VL_MIN((double)width-1,(double)height-1) / (minOctaveSize - 1))) ;
  1429. if (self->method == VL_COVDET_METHOD_DOG) {
  1430. octaveFirstSubdivision = -1 ;
  1431. octaveLastSubdivision = self->octaveResolution + 1 ;
  1432. } else if (self->method == VL_COVDET_METHOD_HESSIAN) {
  1433. octaveFirstSubdivision = -1 ;
  1434. octaveLastSubdivision = self->octaveResolution ;
  1435. } else {
  1436. octaveFirstSubdivision = 0 ;
  1437. octaveLastSubdivision = self->octaveResolution - 1 ;
  1438. }
  1439. geom.width = width ;
  1440. geom.height = height ;
  1441. geom.firstOctave = self->firstOctave ;
  1442. geom.lastOctave = lastOctave ;
  1443. geom.octaveResolution = self->octaveResolution ;
  1444. geom.octaveFirstSubdivision = octaveFirstSubdivision ;
  1445. geom.octaveLastSubdivision = octaveLastSubdivision ;
  1446. if (self->gss == NULL ||
  1447. ! vl_scalespacegeometry_is_equal (geom,
  1448. vl_scalespace_get_geometry(self->gss)))
  1449. {
  1450. if (self->gss) vl_scalespace_delete(self->gss) ;
  1451. self->gss = vl_scalespace_new_with_geometry(geom) ;
  1452. if (self->gss == NULL) return VL_ERR_ALLOC ;
  1453. }
  1454. vl_scalespace_put_image(self->gss, image) ;
  1455. return VL_ERR_OK ;
  1456. }
  1457. /* ---------------------------------------------------------------- */
  1458. /* Cornerness measures */
  1459. /* ---------------------------------------------------------------- */
  1460. /** @brief Scaled derminant of the Hessian filter
  1461. ** @param hessian output image.
  1462. ** @param image input image.
  1463. ** @param width image width.
  1464. ** @param height image height.
  1465. ** @param step image sampling step (pixel size).
  1466. ** @param sigma Gaussian smoothing of the input image.
  1467. **/
  1468. static void
  1469. _vl_det_hessian_response (float * hessian,
  1470. float const * image,
  1471. vl_size width, vl_size height,
  1472. double step, double sigma)
  1473. {
  1474. float factor = (float) pow(sigma/step, 4.0) ;
  1475. vl_index const xo = 1 ; /* x-stride */
  1476. vl_index const yo = width; /* y-stride */
  1477. vl_size r, c;
  1478. float p11, p12, p13, p21, p22, p23, p31, p32, p33;
  1479. /* setup input pointer to be centered at 0,1 */
  1480. float const *in = image + yo ;
  1481. /* setup output pointer to be centered at 1,1 */
  1482. float *out = hessian + xo + yo;
  1483. /* move 3x3 window and convolve */
  1484. for (r = 1; r < height - 1; ++r)
  1485. {
  1486. /* fill in shift registers at the beginning of the row */
  1487. p11 = in[-yo]; p12 = in[xo - yo];
  1488. p21 = in[ 0]; p22 = in[xo ];
  1489. p31 = in[+yo]; p32 = in[xo + yo];
  1490. /* setup input pointer to (2,1) of the 3x3 square */
  1491. in += 2;
  1492. for (c = 1; c < width - 1; ++c)
  1493. {
  1494. float Lxx, Lyy, Lxy;
  1495. /* fetch remaining values (last column) */
  1496. p13 = in[-yo]; p23 = *in; p33 = in[+yo];
  1497. /* Compute 3x3 Hessian values from pixel differences. */
  1498. Lxx = (-p21 + 2*p22 - p23);
  1499. Lyy = (-p12 + 2*p22 - p32);
  1500. Lxy = ((p11 - p31 - p13 + p33)/4.0f);
  1501. /* normalize and write out */
  1502. *out = (Lxx * Lyy - Lxy * Lxy) * factor ;
  1503. /* move window */
  1504. p11=p12; p12=p13;
  1505. p21=p22; p22=p23;
  1506. p31=p32; p32=p33;
  1507. /* move input/output pointers */
  1508. in++; out++;
  1509. }
  1510. out += 2;
  1511. }
  1512. /* Copy the computed values to borders */
  1513. in = hessian + yo + xo ;
  1514. out = hessian + xo ;
  1515. /* Top row without corners */
  1516. memcpy(out, in, (width - 2)*sizeof(float));
  1517. out--;
  1518. in -= yo;
  1519. /* Left border columns without last row */
  1520. for (r = 0; r < height - 1; r++){
  1521. *out = *in;
  1522. *(out + yo - 1) = *(in + yo - 3);
  1523. in += yo;
  1524. out += yo;
  1525. }
  1526. /* Bottom corners */
  1527. in -= yo;
  1528. *out = *in;
  1529. *(out + yo - 1) = *(in + yo - 3);
  1530. /* Bottom row without corners */
  1531. out++;
  1532. memcpy(out, in, (width - 2)*sizeof(float));
  1533. }
  1534. /** @brief Scale-normalised Harris response
  1535. ** @param harris output image.
  1536. ** @param image input image.
  1537. ** @param width image width.
  1538. ** @param height image height.
  1539. ** @param step image sampling step (pixel size).
  1540. ** @param sigma Gaussian smoothing of the input image.
  1541. ** @param sigmaI integration scale.
  1542. ** @param alpha factor in the definition of the Harris score.
  1543. **/
  1544. static void
  1545. _vl_harris_response (float * harris,
  1546. float const * image,
  1547. vl_size width, vl_size height,
  1548. double step, double sigma,
  1549. double sigmaI, double alpha)
  1550. {
  1551. float factor = (float) pow(sigma/step, 4.0) ;
  1552. vl_index k ;
  1553. float * LxLx ;
  1554. float * LyLy ;
  1555. float * LxLy ;
  1556. LxLx = (float*)vl_malloc(sizeof(float) * width * height) ;
  1557. LyLy = (float*)vl_malloc(sizeof(float) * width * height) ;
  1558. LxLy = (float*)vl_malloc(sizeof(float) * width * height) ;
  1559. vl_imgradient_f (LxLx, LyLy, 1, width, image, width, height, width) ;
  1560. for (k = 0 ; k < (signed)(width * height) ; ++k) {
  1561. float dx = LxLx[k] ;
  1562. float dy = LyLy[k] ;
  1563. LxLx[k] = dx*dx ;
  1564. LyLy[k] = dy*dy ;
  1565. LxLy[k] = dx*dy ;
  1566. }
  1567. vl_imsmooth_f(LxLx, width, LxLx, width, height, width,
  1568. sigmaI / step, sigmaI / step) ;
  1569. vl_imsmooth_f(LyLy, width, LyLy, width, height, width,
  1570. sigmaI / step, sigmaI / step) ;
  1571. vl_imsmooth_f(LxLy, width, LxLy, width, height, width,
  1572. sigmaI / step, sigmaI / step) ;
  1573. for (k = 0 ; k < (signed)(width * height) ; ++k) {
  1574. float a = LxLx[k] ;
  1575. float b = LyLy[k] ;
  1576. float c = LxLy[k] ;
  1577. float determinant = a * b - c * c ;
  1578. float trace = a + b ;
  1579. harris[k] = factor * (determinant - alpha * (trace * trace)) ;
  1580. }
  1581. vl_free(LxLy) ;
  1582. vl_free(LyLy) ;
  1583. vl_free(LxLx) ;
  1584. }
  1585. /** @brief Difference of Gaussian
  1586. ** @param dog output image.
  1587. ** @param level1 input image at the smaller Gaussian scale.
  1588. ** @param level2 input image at the larger Gaussian scale.
  1589. ** @param width image width.
  1590. ** @param height image height.
  1591. **/
  1592. static void
  1593. _vl_dog_response (float * dog,
  1594. float const * level1,
  1595. float const * level2,
  1596. vl_size width, vl_size height)
  1597. {
  1598. vl_index k ;
  1599. for (k = 0 ; k < (signed)(width*height) ; ++k) {
  1600. dog[k] = level2[k] - level1[k] ;
  1601. }
  1602. }
  1603. /* ---------------------------------------------------------------- */
  1604. /* Detect features */
  1605. /* ---------------------------------------------------------------- */
  1606. /** @brief Detect scale-space features
  1607. ** @param self object.
  1608. **
  1609. ** This function runs the configured feature detector on the image
  1610. ** that was passed by using ::vl_covdet_put_image.
  1611. **/
  1612. void
  1613. vl_covdet_detect (VlCovDet * self)
  1614. {
  1615. VlScaleSpaceGeometry geom = vl_scalespace_get_geometry(self->gss) ;
  1616. VlScaleSpaceGeometry cgeom ;
  1617. float * levelxx = NULL ;
  1618. float * levelyy = NULL ;
  1619. float * levelxy = NULL ;
  1620. vl_index o, s ;
  1621. assert (self) ;
  1622. assert (self->gss) ;
  1623. /* clear previous detections if any */
  1624. self->numFeatures = 0 ;
  1625. /* prepare buffers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  1626. cgeom = geom ;
  1627. if (self->method == VL_COVDET_METHOD_DOG) {
  1628. cgeom.octaveLastSubdivision -= 1 ;
  1629. }
  1630. if (!self->css ||
  1631. !vl_scalespacegeometry_is_equal(cgeom,
  1632. vl_scalespace_get_geometry(self->css)))
  1633. {
  1634. if (self->css) vl_scalespace_delete(self->css) ;
  1635. self->css = vl_scalespace_new_with_geometry(cgeom) ;
  1636. }
  1637. if (self->method == VL_COVDET_METHOD_HARRIS_LAPLACE ||
  1638. self->method == VL_COVDET_METHOD_MULTISCALE_HARRIS) {
  1639. VlScaleSpaceOctaveGeometry oct = vl_scalespace_get_octave_geometry(self->gss, geom.firstOctave) ;
  1640. levelxx = (float*)vl_malloc(oct.width * oct.height * sizeof(float)) ;
  1641. levelyy = (float*)vl_malloc(oct.width * oct.height * sizeof(float)) ;
  1642. levelxy = (float*)vl_malloc(oct.width * oct.height * sizeof(float)) ;
  1643. }
  1644. /* compute cornerness ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  1645. for (o = cgeom.firstOctave ; o <= cgeom.lastOctave ; ++o) {
  1646. VlScaleSpaceOctaveGeometry oct = vl_scalespace_get_octave_geometry(self->css, o) ;
  1647. for (s = cgeom.octaveFirstSubdivision ; s <= cgeom.octaveLastSubdivision ; ++s) {
  1648. float * level = vl_scalespace_get_level(self->gss, o, s) ;
  1649. float * clevel = vl_scalespace_get_level(self->css, o, s) ;
  1650. double sigma = vl_scalespace_get_level_sigma(self->css, o, s) ;
  1651. switch (self->method) {
  1652. case VL_COVDET_METHOD_DOG:
  1653. _vl_dog_response(clevel,
  1654. vl_scalespace_get_level(self->gss, o, s + 1),
  1655. level,
  1656. oct.width, oct.height) ;
  1657. break ;
  1658. case VL_COVDET_METHOD_HARRIS_LAPLACE:
  1659. case VL_COVDET_METHOD_MULTISCALE_HARRIS:
  1660. _vl_harris_response(clevel,
  1661. level, oct.width, oct.height, oct.step,
  1662. sigma, 1.4 * sigma, 0.05) ;
  1663. break ;
  1664. case VL_COVDET_METHOD_HESSIAN:
  1665. case VL_COVDET_METHOD_HESSIAN_LAPLACE:
  1666. case VL_COVDET_METHOD_MULTISCALE_HESSIAN:
  1667. _vl_det_hessian_response(clevel, level, oct.width, oct.height, oct.step, sigma) ;
  1668. break ;
  1669. default:
  1670. assert(0) ;
  1671. }
  1672. }
  1673. }
  1674. /* find and refine local maxima ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  1675. {
  1676. vl_index * extrema = NULL ;
  1677. vl_size extremaBufferSize = 0 ;
  1678. vl_size numExtrema ;
  1679. vl_size index ;
  1680. for (o = cgeom.firstOctave ; o <= cgeom.lastOctave ; ++o) {
  1681. VlScaleSpaceOctaveGeometry octgeom = vl_scalespace_get_octave_geometry(self->css, o) ;
  1682. double step = octgeom.step ;
  1683. vl_size width = octgeom.width ;
  1684. vl_size height = octgeom.height ;
  1685. vl_size depth = cgeom.octaveLastSubdivision - cgeom.octaveFirstSubdivision + 1 ;
  1686. switch (self->method) {
  1687. case VL_COVDET_METHOD_DOG:
  1688. case VL_COVDET_METHOD_HESSIAN:
  1689. {
  1690. /* scale-space extrema */
  1691. float const * octave =
  1692. vl_scalespace_get_level(self->css, o, cgeom.octaveFirstSubdivision) ;
  1693. numExtrema = vl_find_local_extrema_3(&extrema, &extremaBufferSize,
  1694. octave, width, height, depth,
  1695. 0.8 * self->peakThreshold);
  1696. for (index = 0 ; index < numExtrema ; ++index) {
  1697. VlCovDetExtremum3 refined ;
  1698. VlCovDetFeature feature ;
  1699. vl_bool ok ;
  1700. memset(&feature, 0, sizeof(feature)) ;
  1701. ok = vl_refine_local_extreum_3(&refined,
  1702. octave, width, height, depth,
  1703. extrema[3*index+0],
  1704. extrema[3*index+1],
  1705. extrema[3*index+2]) ;
  1706. ok &= fabs(refined.peakScore) > self->peakThreshold ;
  1707. ok &= refined.edgeScore < self->edgeThreshold ;
  1708. if (ok) {
  1709. double sigma = cgeom.baseScale *
  1710. pow(2.0, (double) o + (refined.z + cgeom.octaveFirstSubdivision)
  1711. / cgeom.octaveResolution) ;
  1712. feature.frame.x = refined.x * step ;
  1713. feature.frame.y = refined.y * step ;
  1714. feature.frame.a11 = sigma ;
  1715. feature.frame.a12 = 0.0 ;
  1716. feature.frame.a21 = 0.0 ;
  1717. feature.frame.a22 = sigma ;
  1718. feature.peakScore = refined.peakScore ;
  1719. feature.edgeScore = refined.edgeScore ;
  1720. vl_covdet_append_feature(self, &feature) ;
  1721. }
  1722. }
  1723. break ;
  1724. }
  1725. default:
  1726. {
  1727. for (s = cgeom.octaveFirstSubdivision ; s < cgeom.octaveLastSubdivision ; ++s) {
  1728. /* space extrema */
  1729. float const * level = vl_scalespace_get_level(self->css,o,s) ;
  1730. numExtrema = vl_find_local_extrema_2(&extrema, &extremaBufferSize,
  1731. level,
  1732. width, height,
  1733. 0.8 * self->peakThreshold);
  1734. for (index = 0 ; index < numExtrema ; ++index) {
  1735. VlCovDetExtremum2 refined ;
  1736. VlCovDetFeature feature ;
  1737. vl_bool ok ;
  1738. memset(&feature, 0, sizeof(feature)) ;
  1739. ok = vl_refine_local_extreum_2(&refined,
  1740. level, width, height,
  1741. extrema[2*index+0],
  1742. extrema[2*index+1]);
  1743. ok &= fabs(refined.peakScore) > self->peakThreshold ;
  1744. ok &= refined.edgeScore < self->edgeThreshold ;
  1745. if (ok) {
  1746. double sigma = cgeom.baseScale *
  1747. pow(2.0, o + (double)s / cgeom.octaveResolution) ;
  1748. feature.frame.x = refined.x * step ;
  1749. feature.frame.y = refined.y * step ;
  1750. feature.frame.a11 = sigma ;
  1751. feature.frame.a12 = 0.0 ;
  1752. feature.frame.a21 = 0.0 ;
  1753. feature.frame.a22 = sigma ;
  1754. feature.peakScore = refined.peakScore ;
  1755. feature.edgeScore = refined.edgeScore ;
  1756. vl_covdet_append_feature(self, &feature) ;
  1757. }
  1758. }
  1759. }
  1760. break ;
  1761. }
  1762. }
  1763. } /* next octave */
  1764. if (extrema) { vl_free(extrema) ; extrema = 0 ; }
  1765. }
  1766. /* Laplacian scale selection for certain methods */
  1767. switch (self->method) {
  1768. case VL_COVDET_METHOD_HARRIS_LAPLACE :
  1769. case VL_COVDET_METHOD_HESSIAN_LAPLACE :
  1770. vl_covdet_extract_laplacian_scales (self) ;
  1771. break ;
  1772. default:
  1773. break ;
  1774. }
  1775. if (self->nonExtremaSuppression) {
  1776. vl_index i, j ;
  1777. double tol = self->nonExtremaSuppression ;
  1778. self->numNonExtremaSuppressed = 0 ;
  1779. for (i = 0 ; i < (signed)self->numFeatures ; ++i) {
  1780. double x = self->features[i].frame.x ;
  1781. double y = self->features[i].frame.y ;
  1782. double sigma = self->features[i].frame.a11 ;
  1783. double score = self->features[i].peakScore ;
  1784. for (j = 0 ; j < (signed)self->numFeatures ; ++j) {
  1785. double dx_ = self->features[j].frame.x - x ;
  1786. double dy_ = self->features[j].frame.y - y ;
  1787. double sigma_ = self->features[j].frame.a11 ;
  1788. double score_ = self->features[j].peakScore ;
  1789. if (score_ == 0) continue ;
  1790. if (sigma < (1+tol) * sigma_ &&
  1791. sigma_ < (1+tol) * sigma &&
  1792. vl_abs_d(dx_) < tol * sigma &&
  1793. vl_abs_d(dy_) < tol * sigma &&
  1794. vl_abs_d(score) > vl_abs_d(score_)) {
  1795. self->features[j].peakScore = 0 ;
  1796. self->numNonExtremaSuppressed ++ ;
  1797. }
  1798. }
  1799. }
  1800. j = 0 ;
  1801. for (i = 0 ; i < (signed)self->numFeatures ; ++i) {
  1802. VlCovDetFeature feature = self->features[i] ;
  1803. if (self->features[i].peakScore != 0) {
  1804. self->features[j++] = feature ;
  1805. }
  1806. }
  1807. self->numFeatures = j ;
  1808. }
  1809. if (levelxx) vl_free(levelxx) ;
  1810. if (levelyy) vl_free(levelyy) ;
  1811. if (levelxy) vl_free(levelxy) ;
  1812. }
  1813. /* ---------------------------------------------------------------- */
  1814. /* Extract patches */
  1815. /* ---------------------------------------------------------------- */
  1816. /** @internal
  1817. ** @brief Helper for extracting patches
  1818. ** @param self object.
  1819. ** @param[out] sigma1 actual patch smoothing along the first axis.
  1820. ** @param[out] sigma2 actual patch smoothing along the second axis.
  1821. ** @param patch buffer.
  1822. ** @param resolution patch resolution.
  1823. ** @param extent patch extent.
  1824. ** @param sigma desired smoothing in the patch frame.
  1825. ** @param A_ linear transfomration from patch to image.
  1826. ** @param T_ translation from patch to image.
  1827. ** @param d1 first singular value @a A.
  1828. ** @param d2 second singular value of @a A.
  1829. **/
  1830. vl_bool
  1831. vl_covdet_extract_patch_helper (VlCovDet * self,
  1832. double * sigma1,
  1833. double * sigma2,
  1834. float * patch,
  1835. vl_size resolution,
  1836. double extent,
  1837. double sigma,
  1838. double A_ [4],
  1839. double T_ [2],
  1840. double d1, double d2)
  1841. {
  1842. vl_index o, s ;
  1843. double factor ;
  1844. double sigma_ ;
  1845. float const * level ;
  1846. vl_size width, height ;
  1847. double step ;
  1848. double A [4] = {A_[0], A_[1], A_[2], A_[3]} ;
  1849. double T [2] = {T_[0], T_[1]} ;
  1850. VlScaleSpaceGeometry geom = vl_scalespace_get_geometry(self->gss) ;
  1851. VlScaleSpaceOctaveGeometry oct ;
  1852. /* Starting from a pre-smoothed image at scale sigma_
  1853. because of the mapping A the resulting smoothing in
  1854. the warped patch is S, where
  1855. sigma_^2 I = A S A',
  1856. S = sigma_^2 inv(A) inv(A)' = sigma_^2 V D^-2 V',
  1857. A = U D V'.
  1858. Thus we rotate A by V to obtain an axis-aligned smoothing:
  1859. A = U*D,
  1860. S = sigma_^2 D^-2.
  1861. Then we search the scale-space for the best sigma_ such
  1862. that the target smoothing is approximated from below:
  1863. max sigma_(o,s) : simga_(o,s) factor <= sigma,
  1864. factor = max{abs(D11), abs(D22)}.
  1865. */
  1866. /*
  1867. Determine the best level (o,s) such that sigma_(o,s) factor <= sigma.
  1868. This can be obtained by scanning octaves from smallest to largest
  1869. and stopping when no level in the octave satisfies the relation.
  1870. Given the range of octave availables, do the best you can.
  1871. */
  1872. factor = 1.0 / VL_MIN(d1, d2) ;
  1873. for (o = geom.firstOctave + 1 ; o <= geom.lastOctave ; ++o) {
  1874. s = vl_floor_d(vl_log2_d(sigma / (factor * geom.baseScale)) - o) ;
  1875. s = VL_MAX(s, geom.octaveFirstSubdivision) ;
  1876. s = VL_MIN(s, geom.octaveLastSubdivision) ;
  1877. sigma_ = geom.baseScale * pow(2.0, o + (double)s / geom.octaveResolution) ;
  1878. /*VL_PRINTF(".. %d D=%g %g; sigma_=%g factor*sigma_=%g\n", o, d1, d2, sigma_, factor* sigma_) ;*/
  1879. if (factor * sigma_ > sigma) {
  1880. o -- ;
  1881. break ;
  1882. }
  1883. }
  1884. o = VL_MIN(o, geom.lastOctave) ;
  1885. s = vl_floor_d(vl_log2_d(sigma / (factor * geom.baseScale)) - o) ;
  1886. s = VL_MAX(s, geom.octaveFirstSubdivision) ;
  1887. s = VL_MIN(s, geom.octaveLastSubdivision) ;
  1888. sigma_ = geom.baseScale * pow(2.0, o + (double)s / geom.octaveResolution) ;
  1889. if (sigma1) *sigma1 = sigma_ / d1 ;
  1890. if (sigma2) *sigma2 = sigma_ / d2 ;
  1891. /*VL_PRINTF("%d %d %g %g %g %g\n", o, s, factor, sigma_, factor * sigma_, sigma) ;*/
  1892. /*
  1893. Now the scale space level to be used for this warping has been
  1894. determined.
  1895. If the patch is partially or completely out of the image boundary,
  1896. create a padded copy of the required region first.
  1897. */
  1898. level = vl_scalespace_get_level(self->gss, o, s) ;
  1899. oct = vl_scalespace_get_octave_geometry(self->gss, o) ;
  1900. width = oct.width ;
  1901. height = oct.height ;
  1902. step = oct.step ;
  1903. A[0] /= step ;
  1904. A[1] /= step ;
  1905. A[2] /= step ;
  1906. A[3] /= step ;
  1907. T[0] /= step ;
  1908. T[1] /= step ;
  1909. {
  1910. /*
  1911. Warp the patch domain [x0hat,y0hat,x1hat,y1hat] to the image domain/
  1912. Obtain a box [x0,y0,x1,y1] enclosing that wrapped box, and then
  1913. an integer vertexes version [x0i, y0i, x1i, y1i], making room
  1914. for one pixel at the boundary to simplify bilinear interpolation
  1915. later on.
  1916. */
  1917. vl_index x0i, y0i, x1i, y1i ;
  1918. double x0 = +VL_INFINITY_D ;
  1919. double x1 = -VL_INFINITY_D ;
  1920. double y0 = +VL_INFINITY_D ;
  1921. double y1 = -VL_INFINITY_D ;
  1922. double boxx [4] = {extent, extent, -extent, -extent} ;
  1923. double boxy [4] = {-extent, extent, extent, -extent} ;
  1924. int i ;
  1925. for (i = 0 ; i < 4 ; ++i) {
  1926. double x = A[0] * boxx[i] + A[2] * boxy[i] + T[0] ;
  1927. double y = A[1] * boxx[i] + A[3] * boxy[i] + T[1] ;
  1928. x0 = VL_MIN(x0, x) ;
  1929. x1 = VL_MAX(x1, x) ;
  1930. y0 = VL_MIN(y0, y) ;
  1931. y1 = VL_MAX(y1, y) ;
  1932. }
  1933. /* Leave one pixel border for bilinear interpolation. */
  1934. x0i = floor(x0) - 1 ;
  1935. y0i = floor(y0) - 1 ;
  1936. x1i = ceil(x1) + 1 ;
  1937. y1i = ceil(y1) + 1 ;
  1938. /*
  1939. If the box [x0i,y0i,x1i,y1i] is not fully contained in the
  1940. image domain, then create a copy of this region by padding
  1941. the image. The image is extended by continuity.
  1942. */
  1943. if (x0i < 0 || x1i > (signed)width-1 ||
  1944. y0i < 0 || y1i > (signed)height-1) {
  1945. vl_index xi, yi ;
  1946. /* compute the amount of l,r,t,b padding needed to complete the patch */
  1947. vl_index padx0 = VL_MAX(0, - x0i) ;
  1948. vl_index pady0 = VL_MAX(0, - y0i) ;
  1949. vl_index padx1 = VL_MAX(0, x1i - ((signed)width - 1)) ;
  1950. vl_index pady1 = VL_MAX(0, y1i - ((signed)height - 1)) ;
  1951. /* make enough room for the patch */
  1952. vl_index patchWidth = x1i - x0i + 1 ;
  1953. vl_index patchHeight = y1i - y0i + 1 ;
  1954. vl_size patchBufferSize = patchWidth * patchHeight * sizeof(float) ;
  1955. if (patchBufferSize > self->patchBufferSize) {
  1956. int err = _vl_resize_buffer((void**)&self->patch, &self->patchBufferSize, patchBufferSize) ;
  1957. if (err) return vl_set_last_error(VL_ERR_ALLOC, NULL) ;
  1958. }
  1959. if (pady0 < patchHeight - pady1) {
  1960. /* start by filling the central horizontal band */
  1961. for (yi = y0i + pady0 ; yi < y0i + patchHeight - pady1 ; ++ yi) {
  1962. float *dst = self->patch + (yi - y0i) * patchWidth ;
  1963. float const *src = level + yi * width + VL_MIN(VL_MAX(0, x0i),(signed)width-1) ;
  1964. for (xi = x0i ; xi < x0i + padx0 ; ++xi) *dst++ = *src ;
  1965. for ( ; xi < x0i + patchWidth - padx1 - 2 ; ++xi) *dst++ = *src++ ;
  1966. for ( ; xi < x0i + patchWidth ; ++xi) *dst++ = *src ;
  1967. }
  1968. /* now extend the central band up and down */
  1969. for (yi = 0 ; yi < pady0 ; ++yi) {
  1970. memcpy(self->patch + yi * patchWidth,
  1971. self->patch + pady0 * patchWidth,
  1972. patchWidth * sizeof(float)) ;
  1973. }
  1974. for (yi = patchHeight - pady1 ; yi < patchHeight ; ++yi) {
  1975. memcpy(self->patch + yi * patchWidth,
  1976. self->patch + (patchHeight - pady1 - 1) * patchWidth,
  1977. patchWidth * sizeof(float)) ;
  1978. }
  1979. } else {
  1980. /* should be handled better! */
  1981. memset(self->patch, 0, self->patchBufferSize) ;
  1982. }
  1983. #if 0
  1984. {
  1985. char name [200] ;
  1986. snprintf(name, 200, "/tmp/%20.0f-ext.pgm", 1e10*vl_get_cpu_time()) ;
  1987. vl_pgm_write_f(name, patch, patchWidth, patchWidth) ;
  1988. }
  1989. #endif
  1990. level = self->patch ;
  1991. width = patchWidth ;
  1992. height = patchHeight ;
  1993. T[0] -= x0i ;
  1994. T[1] -= y0i ;
  1995. }
  1996. }
  1997. /*
  1998. Resample by using bilinear interpolation.
  1999. */
  2000. {
  2001. float * pt = patch ;
  2002. double yhat = -extent ;
  2003. vl_index xxi ;
  2004. vl_index yyi ;
  2005. double stephat = extent / resolution ;
  2006. for (yyi = 0 ; yyi < 2 * (signed)resolution + 1 ; ++yyi) {
  2007. double xhat = -extent ;
  2008. double rx = A[2] * yhat + T[0] ;
  2009. double ry = A[3] * yhat + T[1] ;
  2010. for (xxi = 0 ; xxi < 2 * (signed)resolution + 1 ; ++xxi) {
  2011. double x = A[0] * xhat + rx ;
  2012. double y = A[1] * xhat + ry ;
  2013. vl_index xi = vl_floor_d(x) ;
  2014. vl_index yi = vl_floor_d(y) ;
  2015. double i00 = level[yi * width + xi] ;
  2016. double i10 = level[yi * width + xi + 1] ;
  2017. double i01 = level[(yi + 1) * width + xi] ;
  2018. double i11 = level[(yi + 1) * width + xi + 1] ;
  2019. double wx = x - xi ;
  2020. double wy = y - yi ;
  2021. assert(xi >= 0 && xi <= (signed)width - 1) ;
  2022. assert(yi >= 0 && yi <= (signed)height - 1) ;
  2023. *pt++ =
  2024. (1.0 - wy) * ((1.0 - wx) * i00 + wx * i10) +
  2025. wy * ((1.0 - wx) * i01 + wx * i11) ;
  2026. xhat += stephat ;
  2027. }
  2028. yhat += stephat ;
  2029. }
  2030. }
  2031. #if 0
  2032. {
  2033. char name [200] ;
  2034. snprintf(name, 200, "/tmp/%20.0f.pgm", 1e10*vl_get_cpu_time()) ;
  2035. vl_pgm_write_f(name, patch, 2*resolution+1, 2*resolution+1) ;
  2036. }
  2037. #endif
  2038. return VL_ERR_OK ;
  2039. }
  2040. /** @brief Helper for extracting patches
  2041. ** @param self object.
  2042. ** @param patch buffer.
  2043. ** @param resolution patch resolution.
  2044. ** @param extent patch extent.
  2045. ** @param sigma desired smoothing in the patch frame.
  2046. ** @param frame feature frame.
  2047. **
  2048. ** The function considers a patch of extent <code>[-extent,extent]</code>
  2049. ** on each side, with a side counting <code>2*resolution+1</code> pixels.
  2050. ** In attempts to extract from the scale space a patch
  2051. ** based on the affine warping specified by @a frame in such a way
  2052. ** that the resulting smoothing of the image is @a sigma (in the
  2053. ** patch frame).
  2054. **
  2055. ** The transformation is specified by the matrices @c A and @c T
  2056. ** embedded in the feature @a frame. Note that this transformation maps
  2057. ** pixels from the patch frame to the image frame.
  2058. **/
  2059. vl_bool
  2060. vl_covdet_extract_patch_for_frame (VlCovDet * self,
  2061. float * patch,
  2062. vl_size resolution,
  2063. double extent,
  2064. double sigma,
  2065. VlFrameOrientedEllipse frame)
  2066. {
  2067. double A[2*2] = {frame.a11, frame.a21, frame.a12, frame.a22} ;
  2068. double T[2] = {frame.x, frame.y} ;
  2069. double D[4], U[4], V[4] ;
  2070. vl_svd2(D, U, V, A) ;
  2071. return vl_covdet_extract_patch_helper
  2072. (self, NULL, NULL, patch, resolution, extent, sigma, A, T, D[0], D[3]) ;
  2073. }
  2074. /* ---------------------------------------------------------------- */
  2075. /* Affine shape */
  2076. /* ---------------------------------------------------------------- */
  2077. /** @brief Extract the affine shape for a feature frame
  2078. ** @param self object.
  2079. ** @param adapted the shape-adapted frame.
  2080. ** @param frame the input frame.
  2081. ** @return ::VL_ERR_OK if affine adaptation is successful.
  2082. **
  2083. ** This function may fail if adaptation is unsuccessful or if
  2084. ** memory is insufficient.
  2085. **/
  2086. int
  2087. vl_covdet_extract_affine_shape_for_frame (VlCovDet * self,
  2088. VlFrameOrientedEllipse * adapted,
  2089. VlFrameOrientedEllipse frame)
  2090. {
  2091. vl_index iter = 0 ;
  2092. double A [2*2] = {frame.a11, frame.a21, frame.a12, frame.a22} ;
  2093. double T [2] = {frame.x, frame.y} ;
  2094. double U [2*2] ;
  2095. double V [2*2] ;
  2096. double D [2*2] ;
  2097. double M [2*2] ;
  2098. double P [2*2] ;
  2099. double P_ [2*2] ;
  2100. double Q [2*2] ;
  2101. double sigma1, sigma2 ;
  2102. double sigmaD = VL_COVDET_AA_RELATIVE_DERIVATIVE_SIGMA ;
  2103. double factor ;
  2104. double anisotropy ;
  2105. double referenceScale ;
  2106. vl_size const resolution = VL_COVDET_AA_PATCH_RESOLUTION ;
  2107. vl_size const side = 2*VL_COVDET_AA_PATCH_RESOLUTION + 1 ;
  2108. double const extent = VL_COVDET_AA_PATCH_EXTENT ;
  2109. *adapted = frame ;
  2110. while (1) {
  2111. double lxx = 0, lxy = 0, lyy = 0 ;
  2112. vl_index k ;
  2113. int err ;
  2114. /* A = U D V' */
  2115. vl_svd2(D, U, V, A) ;
  2116. anisotropy = VL_MAX(D[0]/D[3], D[3]/D[0]) ;
  2117. /* VL_PRINTF("anisot: %g\n", anisotropy); */
  2118. if (anisotropy > VL_COVDET_AA_MAX_ANISOTROPY) {
  2119. /* diverged, give up with current solution */
  2120. break ;
  2121. }
  2122. /* make sure that the smallest singluar value stays fixed
  2123. after the first iteration */
  2124. if (iter == 0) {
  2125. referenceScale = VL_MIN(D[0], D[3]) ;
  2126. factor = 1.0 ;
  2127. } else {
  2128. factor = referenceScale / VL_MIN(D[0],D[3]) ;
  2129. }
  2130. D[0] *= factor ;
  2131. D[3] *= factor ;
  2132. A[0] = U[0] * D[0] ;
  2133. A[1] = U[1] * D[0] ;
  2134. A[2] = U[2] * D[3] ;
  2135. A[3] = U[3] * D[3] ;
  2136. adapted->a11 = A[0] ;
  2137. adapted->a21 = A[1] ;
  2138. adapted->a12 = A[2] ;
  2139. adapted->a22 = A[3] ;
  2140. if (++iter >= VL_COVDET_AA_MAX_NUM_ITERATIONS) break ;
  2141. err = vl_covdet_extract_patch_helper(self,
  2142. &sigma1, &sigma2,
  2143. self->aaPatch,
  2144. resolution,
  2145. extent,
  2146. sigmaD,
  2147. A, T, D[0], D[3]) ;
  2148. if (err) return err ;
  2149. if (self->aaAccurateSmoothing ) {
  2150. double deltaSigma1 = sqrt(VL_MAX(sigmaD*sigmaD - sigma1*sigma1,0)) ;
  2151. double deltaSigma2 = sqrt(VL_MAX(sigmaD*sigmaD - sigma2*sigma2,0)) ;
  2152. double stephat = extent / resolution ;
  2153. vl_imsmooth_f(self->aaPatch, side,
  2154. self->aaPatch, side, side, side,
  2155. deltaSigma1 / stephat, deltaSigma2 / stephat) ;
  2156. }
  2157. /* compute second moment matrix */
  2158. vl_imgradient_f (self->aaPatchX, self->aaPatchY, 1, side,
  2159. self->aaPatch, side, side, side) ;
  2160. for (k = 0 ; k < (signed)(side*side) ; ++k) {
  2161. double lx = self->aaPatchX[k] ;
  2162. double ly = self->aaPatchY[k] ;
  2163. lxx += lx * lx * self->aaMask[k] ;
  2164. lyy += ly * ly * self->aaMask[k] ;
  2165. lxy += lx * ly * self->aaMask[k] ;
  2166. }
  2167. M[0] = lxx ;
  2168. M[1] = lxy ;
  2169. M[2] = lxy ;
  2170. M[3] = lyy ;
  2171. if (lxx == 0 || lyy == 0) {
  2172. *adapted = frame ;
  2173. break ;
  2174. }
  2175. /* decompose M = P * Q * P' */
  2176. vl_svd2 (Q, P, P_, M) ;
  2177. /*
  2178. Setting A <- A * dA results in M to change approximatively as
  2179. M --> dA' M dA = dA' P Q P dA
  2180. To make this proportional to the identity, we set
  2181. dA ~= P Q^1/2
  2182. we also make it so the smallest singular value of A is unchanged.
  2183. */
  2184. if (Q[3]/Q[0] < VL_COVDET_AA_CONVERGENCE_THRESHOLD &&
  2185. Q[0]/Q[3] < VL_COVDET_AA_CONVERGENCE_THRESHOLD) {
  2186. break ;
  2187. }
  2188. {
  2189. double Ap [4] ;
  2190. double q0 = sqrt(Q[0]) ;
  2191. double q1 = sqrt(Q[3]) ;
  2192. Ap[0] = (A[0] * P[0] + A[2] * P[1]) / q0 ;
  2193. Ap[1] = (A[1] * P[0] + A[3] * P[1]) / q0 ;
  2194. Ap[2] = (A[0] * P[2] + A[2] * P[3]) / q1 ;
  2195. Ap[3] = (A[1] * P[2] + A[3] * P[3]) / q1 ;
  2196. memcpy(A,Ap,4*sizeof(double)) ;
  2197. }
  2198. } /* next iteration */
  2199. /*
  2200. Make upright.
  2201. Shape adaptation does not estimate rotation. This is fixed by default
  2202. so that a selected axis is not rotated at all (usually this is the
  2203. vertical axis for upright features). To do so, the frame is rotated
  2204. as follows.
  2205. */
  2206. {
  2207. double A [2*2] = {adapted->a11, adapted->a21, adapted->a12, adapted->a22} ;
  2208. double ref [2] ;
  2209. double ref_ [2] ;
  2210. double angle ;
  2211. double angle_ ;
  2212. double dangle ;
  2213. double r1, r2 ;
  2214. if (self->transposed) {
  2215. /* up is the x axis */
  2216. ref[0] = 1 ;
  2217. ref[1] = 0 ;
  2218. } else {
  2219. /* up is the y axis */
  2220. ref[0] = 0 ;
  2221. ref[1] = 1 ;
  2222. }
  2223. vl_solve_linear_system_2 (ref_, A, ref) ;
  2224. angle = atan2(ref[1], ref[0]) ;
  2225. angle_ = atan2(ref_[1], ref_[0]) ;
  2226. dangle = angle_ - angle ;
  2227. r1 = cos(dangle) ;
  2228. r2 = sin(dangle) ;
  2229. adapted->a11 = + A[0] * r1 + A[2] * r2 ;
  2230. adapted->a21 = + A[1] * r1 + A[3] * r2 ;
  2231. adapted->a12 = - A[0] * r2 + A[2] * r1 ;
  2232. adapted->a22 = - A[1] * r2 + A[3] * r1 ;
  2233. }
  2234. return VL_ERR_OK ;
  2235. }
  2236. /** @brief Extract the affine shape for the stored features
  2237. ** @param self object.
  2238. **
  2239. ** This function may discard features for which no affine
  2240. ** shape can reliably be detected.
  2241. **/
  2242. void
  2243. vl_covdet_extract_affine_shape (VlCovDet * self)
  2244. {
  2245. vl_index i, j = 0 ;
  2246. vl_size numFeatures = vl_covdet_get_num_features(self) ;
  2247. VlCovDetFeature * feature = (VlCovDetFeature*) vl_covdet_get_features(self);
  2248. for (i = 0 ; i < (signed)numFeatures ; ++i) {
  2249. int status ;
  2250. VlFrameOrientedEllipse adapted ;
  2251. status = vl_covdet_extract_affine_shape_for_frame(self, &adapted, feature[i].frame) ;
  2252. if (status == VL_ERR_OK) {
  2253. feature[j] = feature[i] ;
  2254. feature[j].frame = adapted ;
  2255. ++ j ;
  2256. }
  2257. }
  2258. self->numFeatures = j ;
  2259. }
  2260. /* ---------------------------------------------------------------- */
  2261. /* Orientation */
  2262. /* ---------------------------------------------------------------- */
  2263. static int
  2264. _vl_covdet_compare_orientations_descending (void const * a_,
  2265. void const * b_)
  2266. {
  2267. VlCovDetFeatureOrientation const * a = (VlCovDetFeatureOrientation*) a_ ;
  2268. VlCovDetFeatureOrientation const * b = (VlCovDetFeatureOrientation*)b_ ;
  2269. if (a->score > b->score) return -1 ;
  2270. if (a->score < b->score) return +1 ;
  2271. return 0 ;
  2272. }
  2273. /** @brief Extract the orientation(s) for a feature
  2274. ** @param self object.
  2275. ** @param numOrientations the number of detected orientations.
  2276. ** @param frame pose of the feature.
  2277. ** @return an array of detected orientations with their scores.
  2278. **
  2279. ** The returned array is a matrix of size @f$ 2 \times n @f$
  2280. ** where <em>n</em> is the number of detected orientations.
  2281. **
  2282. ** The function returns @c NULL if memory is insufficient.
  2283. **/
  2284. VlCovDetFeatureOrientation *
  2285. vl_covdet_extract_orientations_for_frame (VlCovDet * self,
  2286. vl_size * numOrientations,
  2287. VlFrameOrientedEllipse frame)
  2288. {
  2289. int err ;
  2290. vl_index k, i ;
  2291. vl_index iter ;
  2292. double extent = VL_COVDET_AA_PATCH_EXTENT ;
  2293. vl_size resolution = VL_COVDET_AA_PATCH_RESOLUTION ;
  2294. vl_size side = 2 * resolution + 1 ;
  2295. vl_size const numBins = VL_COVDET_OR_NUM_ORIENTATION_HISTOGAM_BINS ;
  2296. double hist [VL_COVDET_OR_NUM_ORIENTATION_HISTOGAM_BINS] ;
  2297. double const binExtent = 2 * VL_PI / VL_COVDET_OR_NUM_ORIENTATION_HISTOGAM_BINS ;
  2298. double const peakRelativeSize = VL_COVDET_OR_ADDITIONAL_PEAKS_RELATIVE_SIZE ;
  2299. double maxPeakValue ;
  2300. double A [2*2] = {frame.a11, frame.a21, frame.a12, frame.a22} ;
  2301. double T [2] = {frame.x, frame.y} ;
  2302. double U [2*2] ;
  2303. double V [2*2] ;
  2304. double D [2*2] ;
  2305. double sigma1, sigma2 ;
  2306. double sigmaD = 1.0 ;
  2307. double theta0 ;
  2308. assert(self);
  2309. assert(numOrientations) ;
  2310. /*
  2311. The goal is to estimate a rotation R(theta) such that the patch given
  2312. by the transformation A R(theta) has the strongest average
  2313. gradient pointing right (or down for transposed conventions).
  2314. To compensate for tha anisotropic smoothing due to warping,
  2315. A is decomposed as A = U D V' and the patch is warped by
  2316. U D only, meaning that the matrix R_(theta) will be estimated instead,
  2317. where:
  2318. A R(theta) = U D V' R(theta) = U D R_(theta)
  2319. such that R(theta) = V R(theta). That is an extra rotation of
  2320. theta0 = atan2(V(2,1),V(1,1)).
  2321. */
  2322. /* axis aligned anisotropic smoothing for easier compensation */
  2323. vl_svd2(D, U, V, A) ;
  2324. A[0] = U[0] * D[0] ;
  2325. A[1] = U[1] * D[0] ;
  2326. A[2] = U[2] * D[3] ;
  2327. A[3] = U[3] * D[3] ;
  2328. theta0 = atan2(V[1],V[0]) ;
  2329. err = vl_covdet_extract_patch_helper(self,
  2330. &sigma1, &sigma2,
  2331. self->aaPatch,
  2332. resolution,
  2333. extent,
  2334. sigmaD,
  2335. A, T, D[0], D[3]) ;
  2336. if (err) {
  2337. *numOrientations = 0 ;
  2338. return NULL ;
  2339. }
  2340. if (1) {
  2341. double deltaSigma1 = sqrt(VL_MAX(sigmaD*sigmaD - sigma1*sigma1,0)) ;
  2342. double deltaSigma2 = sqrt(VL_MAX(sigmaD*sigmaD - sigma2*sigma2,0)) ;
  2343. double stephat = extent / resolution ;
  2344. vl_imsmooth_f(self->aaPatch, side,
  2345. self->aaPatch, side, side, side,
  2346. deltaSigma1 / stephat, deltaSigma2 / stephat) ;
  2347. }
  2348. /* histogram of oriented gradients */
  2349. vl_imgradient_polar_f (self->aaPatchX, self->aaPatchY, 1, side,
  2350. self->aaPatch, side, side, side) ;
  2351. memset (hist, 0, sizeof(double) * numBins) ;
  2352. for (k = 0 ; k < (signed)(side*side) ; ++k) {
  2353. double modulus = self->aaPatchX[k] ;
  2354. double angle = self->aaPatchY[k] ;
  2355. double weight = self->aaMask[k] ;
  2356. double x = angle / binExtent ;
  2357. vl_index bin = vl_floor_d(x) ;
  2358. double w2 = x - bin ;
  2359. double w1 = 1.0 - w2 ;
  2360. hist[(bin + numBins) % numBins] += w1 * (modulus * weight) ;
  2361. hist[(bin + numBins + 1) % numBins] += w2 * (modulus * weight) ;
  2362. }
  2363. /* smooth histogram */
  2364. for (iter = 0; iter < 6; iter ++) {
  2365. double prev = hist [numBins - 1] ;
  2366. double first = hist [0] ;
  2367. vl_index i ;
  2368. for (i = 0; i < (signed)numBins - 1; ++i) {
  2369. double curr = (prev + hist[i] + hist[(i + 1) % numBins]) / 3.0 ;
  2370. prev = hist[i] ;
  2371. hist[i] = curr ;
  2372. }
  2373. hist[i] = (prev + hist[i] + first) / 3.0 ;
  2374. }
  2375. /* find the histogram maximum */
  2376. maxPeakValue = 0 ;
  2377. for (i = 0 ; i < (signed)numBins ; ++i) {
  2378. maxPeakValue = VL_MAX (maxPeakValue, hist[i]) ;
  2379. }
  2380. /* find peaks within 80% from max */
  2381. *numOrientations = 0 ;
  2382. for(i = 0 ; i < (signed)numBins ; ++i) {
  2383. double h0 = hist [i] ;
  2384. double hm = hist [(i - 1 + numBins) % numBins] ;
  2385. double hp = hist [(i + 1 + numBins) % numBins] ;
  2386. /* is this a peak? */
  2387. if (h0 > peakRelativeSize * maxPeakValue && h0 > hm && h0 > hp) {
  2388. /* quadratic interpolation */
  2389. double di = - 0.5 * (hp - hm) / (hp + hm - 2 * h0) ;
  2390. double th = binExtent * (i + di) + theta0 ;
  2391. if (self->transposed) {
  2392. /* the axis to the right is y, measure orientations from this */
  2393. th = th - VL_PI/2 ;
  2394. }
  2395. self->orientations[*numOrientations].angle = th ;
  2396. self->orientations[*numOrientations].score = h0 ;
  2397. *numOrientations += 1 ;
  2398. //VL_PRINTF("%d %g\n", *numOrientations, th) ;
  2399. if (*numOrientations >= VL_COVDET_MAX_NUM_ORIENTATIONS) break ;
  2400. }
  2401. }
  2402. /* sort the orientations by decreasing scores */
  2403. qsort(self->orientations,
  2404. *numOrientations,
  2405. sizeof(VlCovDetFeatureOrientation),
  2406. _vl_covdet_compare_orientations_descending) ;
  2407. return self->orientations ;
  2408. }
  2409. /** @brief Extract the orientation(s) for the stored features.
  2410. ** @param self object.
  2411. **
  2412. ** Note that, since more than one orientation can be detected
  2413. ** for each feature, this function may create copies of them,
  2414. ** one for each orientation.
  2415. **/
  2416. void
  2417. vl_covdet_extract_orientations (VlCovDet * self)
  2418. {
  2419. vl_index i, j ;
  2420. vl_size numFeatures = vl_covdet_get_num_features(self) ;
  2421. for (i = 0 ; i < (signed)numFeatures ; ++i) {
  2422. vl_size numOrientations ;
  2423. VlCovDetFeature feature = self->features[i] ;
  2424. VlCovDetFeatureOrientation* orientations =
  2425. vl_covdet_extract_orientations_for_frame(self, &numOrientations, feature.frame) ;
  2426. for (j = 0 ; j < (signed)numOrientations ; ++j) {
  2427. double A [2*2] = {
  2428. feature.frame.a11,
  2429. feature.frame.a21,
  2430. feature.frame.a12,
  2431. feature.frame.a22} ;
  2432. double r1 = cos(orientations[j].angle) ;
  2433. double r2 = sin(orientations[j].angle) ;
  2434. VlCovDetFeature * oriented ;
  2435. if (j == 0) {
  2436. oriented = & self->features[i] ;
  2437. } else {
  2438. vl_covdet_append_feature(self, &feature) ;
  2439. oriented = & self->features[self->numFeatures -1] ;
  2440. }
  2441. oriented->orientationScore = orientations[j].score ;
  2442. oriented->frame.a11 = + A[0] * r1 + A[2] * r2 ;
  2443. oriented->frame.a21 = + A[1] * r1 + A[3] * r2 ;
  2444. oriented->frame.a12 = - A[0] * r2 + A[2] * r1 ;
  2445. oriented->frame.a22 = - A[1] * r2 + A[3] * r1 ;
  2446. }
  2447. }
  2448. }
  2449. /* ---------------------------------------------------------------- */
  2450. /* Laplacian scales */
  2451. /* ---------------------------------------------------------------- */
  2452. /** @brief Extract the Laplacian scale(s) for a feature frame.
  2453. ** @param self object.
  2454. ** @param numScales the number of detected scales.
  2455. ** @param frame pose of the feature.
  2456. ** @return an array of detected scales.
  2457. **
  2458. ** The function returns @c NULL if memory is insufficient.
  2459. **/
  2460. VlCovDetFeatureLaplacianScale *
  2461. vl_covdet_extract_laplacian_scales_for_frame (VlCovDet * self,
  2462. vl_size * numScales,
  2463. VlFrameOrientedEllipse frame)
  2464. {
  2465. /*
  2466. We try to explore one octave, with the nominal detection scale 1.0
  2467. (in the patch reference frame) in the middle. Thus the goal is to sample
  2468. the response of the tr-Laplacian operator at logarithmically
  2469. spaced scales in 1/sqrt(2), sqrt(2).
  2470. To this end, the patch is warped with a smoothing of at most
  2471. sigmaImage = 1 / sqrt(2) (beginning of the scale), sampled at
  2472. roughly twice the Nyquist frequency (so step = 1 / (2*sqrt(2))).
  2473. This maes it possible to approximate the Laplacian operator at
  2474. that scale by simple finite differences.
  2475. */
  2476. int err ;
  2477. double const sigmaImage = 1.0 / sqrt(2.0) ;
  2478. double const step = 0.5 * sigmaImage ;
  2479. double actualSigmaImage ;
  2480. vl_size const resolution = VL_COVDET_LAP_PATCH_RESOLUTION ;
  2481. vl_size const num = 2 * resolution + 1 ;
  2482. double extent = step * resolution ;
  2483. double scores [VL_COVDET_LAP_NUM_LEVELS] ;
  2484. double factor = 1.0 ;
  2485. float const * pt ;
  2486. vl_index k ;
  2487. double A[2*2] = {frame.a11, frame.a21, frame.a12, frame.a22} ;
  2488. double T[2] = {frame.x, frame.y} ;
  2489. double D[4], U[4], V[4] ;
  2490. double sigma1, sigma2 ;
  2491. assert(self) ;
  2492. assert(numScales) ;
  2493. *numScales = 0 ;
  2494. vl_svd2(D, U, V, A) ;
  2495. err = vl_covdet_extract_patch_helper
  2496. (self, &sigma1, &sigma2, self->lapPatch, resolution, extent, sigmaImage, A, T, D[0], D[3]) ;
  2497. if (err) return NULL ;
  2498. /* the actual smoothing after warping is never the target one */
  2499. if (sigma1 == sigma2) {
  2500. actualSigmaImage = sigma1 ;
  2501. } else {
  2502. /* here we could compensate */
  2503. actualSigmaImage = sqrt(sigma1*sigma2) ;
  2504. }
  2505. /* now multiply by the bank of Laplacians */
  2506. pt = self->laplacians ;
  2507. for (k = 0 ; k < VL_COVDET_LAP_NUM_LEVELS ; ++k) {
  2508. vl_index q ;
  2509. double score = 0 ;
  2510. double sigmaLap = pow(2.0, -0.5 + (double)k / (VL_COVDET_LAP_NUM_LEVELS - 1)) ;
  2511. /* note that the sqrt argument cannot be negative since by construction
  2512. sigmaLap >= sigmaImage */
  2513. sigmaLap = sqrt(sigmaLap*sigmaLap
  2514. - sigmaImage*sigmaImage
  2515. + actualSigmaImage*actualSigmaImage) ;
  2516. for (q = 0 ; q < (signed)(num * num) ; ++q) {
  2517. score += (*pt++) * self->lapPatch[q] ;
  2518. }
  2519. scores[k] = score * sigmaLap * sigmaLap ;
  2520. }
  2521. /* find and interpolate maxima */
  2522. for (k = 1 ; k < VL_COVDET_LAP_NUM_LEVELS - 1 ; ++k) {
  2523. double a = scores[k-1] ;
  2524. double b = scores[k] ;
  2525. double c = scores[k+1] ;
  2526. double t = self->lapPeakThreshold ;
  2527. if ((((b > a) && (b > c)) || ((b < a) && (b < c))) && (vl_abs_d(b) >= t)) {
  2528. double dk = - 0.5 * (c - a) / (c + a - 2 * b) ;
  2529. double s = k + dk ;
  2530. double sigmaLap = pow(2.0, -0.5 + s / (VL_COVDET_LAP_NUM_LEVELS - 1)) ;
  2531. double scale ;
  2532. sigmaLap = sqrt(sigmaLap*sigmaLap
  2533. - sigmaImage*sigmaImage
  2534. + actualSigmaImage*actualSigmaImage) ;
  2535. scale = sigmaLap / 1.0 ;
  2536. /*
  2537. VL_PRINTF("** k:%d, s:%f, sigmaLapFilter:%f, sigmaLap%f, scale:%f (%f %f %f)\n",
  2538. k,s,sigmaLapFilter,sigmaLap,scale,a,b,c) ;
  2539. */
  2540. if (*numScales < VL_COVDET_MAX_NUM_LAPLACIAN_SCALES) {
  2541. self->scales[*numScales].scale = scale * factor ;
  2542. self->scales[*numScales].score = b + 0.5 * (c - a) * dk ;
  2543. *numScales += 1 ;
  2544. }
  2545. }
  2546. }
  2547. return self->scales ;
  2548. }
  2549. /** @brief Extract the Laplacian scales for the stored features
  2550. ** @param self object.
  2551. **
  2552. ** Note that, since more than one orientation can be detected
  2553. ** for each feature, this function may create copies of them,
  2554. ** one for each orientation.
  2555. **/
  2556. void
  2557. vl_covdet_extract_laplacian_scales (VlCovDet * self)
  2558. {
  2559. vl_index i, j ;
  2560. vl_bool dropFeaturesWithoutScale = VL_TRUE ;
  2561. vl_size numFeatures = vl_covdet_get_num_features(self) ;
  2562. memset(self->numFeaturesWithNumScales, 0,
  2563. sizeof(self->numFeaturesWithNumScales)) ;
  2564. for (i = 0 ; i < (signed)numFeatures ; ++i) {
  2565. vl_size numScales ;
  2566. VlCovDetFeature feature = self->features[i] ;
  2567. VlCovDetFeatureLaplacianScale const * scales =
  2568. vl_covdet_extract_laplacian_scales_for_frame(self, &numScales, feature.frame) ;
  2569. self->numFeaturesWithNumScales[numScales] ++ ;
  2570. if (numScales == 0 && dropFeaturesWithoutScale) {
  2571. self->features[i].peakScore = 0 ;
  2572. }
  2573. for (j = 0 ; j < (signed)numScales ; ++j) {
  2574. VlCovDetFeature * scaled ;
  2575. if (j == 0) {
  2576. scaled = & self->features[i] ;
  2577. } else {
  2578. vl_covdet_append_feature(self, &feature) ;
  2579. scaled = & self->features[self->numFeatures -1] ;
  2580. }
  2581. scaled->laplacianScaleScore = scales[j].score ;
  2582. scaled->frame.a11 *= scales[j].scale ;
  2583. scaled->frame.a21 *= scales[j].scale ;
  2584. scaled->frame.a12 *= scales[j].scale ;
  2585. scaled->frame.a22 *= scales[j].scale ;
  2586. }
  2587. }
  2588. if (dropFeaturesWithoutScale) {
  2589. j = 0 ;
  2590. for (i = 0 ; i < (signed)self->numFeatures ; ++i) {
  2591. VlCovDetFeature feature = self->features[i] ;
  2592. if (feature.peakScore) {
  2593. self->features[j++] = feature ;
  2594. }
  2595. }
  2596. self->numFeatures = j ;
  2597. }
  2598. }
  2599. /* ---------------------------------------------------------------- */
  2600. /* Checking that features are inside an image */
  2601. /* ---------------------------------------------------------------- */
  2602. vl_bool
  2603. _vl_covdet_check_frame_inside (VlCovDet * self, VlFrameOrientedEllipse frame, double margin)
  2604. {
  2605. double extent = margin ;
  2606. double A [2*2] = {frame.a11, frame.a21, frame.a12, frame.a22} ;
  2607. double T[2] = {frame.x, frame.y} ;
  2608. double x0 = +VL_INFINITY_D ;
  2609. double x1 = -VL_INFINITY_D ;
  2610. double y0 = +VL_INFINITY_D ;
  2611. double y1 = -VL_INFINITY_D ;
  2612. double boxx [4] = {extent, extent, -extent, -extent} ;
  2613. double boxy [4] = {-extent, extent, extent, -extent} ;
  2614. VlScaleSpaceGeometry geom = vl_scalespace_get_geometry(self->gss) ;
  2615. int i ;
  2616. for (i = 0 ; i < 4 ; ++i) {
  2617. double x = A[0] * boxx[i] + A[2] * boxy[i] + T[0] ;
  2618. double y = A[1] * boxx[i] + A[3] * boxy[i] + T[1] ;
  2619. x0 = VL_MIN(x0, x) ;
  2620. x1 = VL_MAX(x1, x) ;
  2621. y0 = VL_MIN(y0, y) ;
  2622. y1 = VL_MAX(y1, y) ;
  2623. }
  2624. return
  2625. 0 <= x0 && x1 <= geom.width-1 &&
  2626. 0 <= y0 && y1 <= geom.height-1 ;
  2627. }
  2628. /** @brief Drop features (partially) outside the image
  2629. ** @param self object.
  2630. ** @param margin geometric marging.
  2631. **
  2632. ** The feature extent is defined by @c maring. A bounding box
  2633. ** in the normalised feature frame containin a circle of radius
  2634. ** @a maring is created and mapped to the image by
  2635. ** the feature frame transformation. Then the feature
  2636. ** is dropped if the bounding box is not contained in the image.
  2637. **
  2638. ** For example, setting @c margin to zero drops a feature only
  2639. ** if its center is not contained.
  2640. **
  2641. ** Typically a valua of @c margin equal to 1 or 2 is used.
  2642. **/
  2643. void
  2644. vl_covdet_drop_features_outside (VlCovDet * self, double margin)
  2645. {
  2646. vl_index i, j = 0 ;
  2647. vl_size numFeatures = vl_covdet_get_num_features(self) ;
  2648. for (i = 0 ; i < (signed)numFeatures ; ++i) {
  2649. vl_bool inside =
  2650. _vl_covdet_check_frame_inside (self, self->features[i].frame, margin) ;
  2651. if (inside) {
  2652. self->features[j] = self->features[i] ;
  2653. ++j ;
  2654. }
  2655. }
  2656. self->numFeatures = j ;
  2657. }
  2658. /* ---------------------------------------------------------------- */
  2659. /* Setters and getters */
  2660. /* ---------------------------------------------------------------- */
  2661. /* ---------------------------------------------------------------- */
  2662. /** @brief Get wether images are passed in transposed
  2663. ** @param self object.
  2664. ** @return whether images are transposed.
  2665. **/
  2666. vl_bool
  2667. vl_covdet_get_transposed (VlCovDet const * self)
  2668. {
  2669. return self->transposed ;
  2670. }
  2671. /** @brief Set the index of the first octave
  2672. ** @param self object.
  2673. ** @param t whether images are transposed.
  2674. **/
  2675. void
  2676. vl_covdet_set_transposed (VlCovDet * self, vl_bool t)
  2677. {
  2678. self->transposed = t ;
  2679. }
  2680. /* ---------------------------------------------------------------- */
  2681. /** @brief Get the edge threshold
  2682. ** @param self object.
  2683. ** @return the edge threshold.
  2684. **/
  2685. double
  2686. vl_covdet_get_edge_threshold (VlCovDet const * self)
  2687. {
  2688. return self->edgeThreshold ;
  2689. }
  2690. /** @brief Set the edge threshold
  2691. ** @param self object.
  2692. ** @param edgeThreshold the edge threshold.
  2693. **
  2694. ** The edge threshold must be non-negative.
  2695. **/
  2696. void
  2697. vl_covdet_set_edge_threshold (VlCovDet * self, double edgeThreshold)
  2698. {
  2699. assert(edgeThreshold >= 0) ;
  2700. self->edgeThreshold = edgeThreshold ;
  2701. }
  2702. /* ---------------------------------------------------------------- */
  2703. /** @brief Get the peak threshold
  2704. ** @param self object.
  2705. ** @return the peak threshold.
  2706. **/
  2707. double
  2708. vl_covdet_get_peak_threshold (VlCovDet const * self)
  2709. {
  2710. return self->peakThreshold ;
  2711. }
  2712. /** @brief Set the peak threshold
  2713. ** @param self object.
  2714. ** @param peakThreshold the peak threshold.
  2715. **
  2716. ** The peak threshold must be non-negative.
  2717. **/
  2718. void
  2719. vl_covdet_set_peak_threshold (VlCovDet * self, double peakThreshold)
  2720. {
  2721. assert(peakThreshold >= 0) ;
  2722. self->peakThreshold = peakThreshold ;
  2723. }
  2724. /* ---------------------------------------------------------------- */
  2725. /** @brief Get the Laplacian peak threshold
  2726. ** @param self object.
  2727. ** @return the Laplacian peak threshold.
  2728. **
  2729. ** This parameter affects only the detecors using the Laplacian
  2730. ** scale selectino method such as Harris-Laplace.
  2731. **/
  2732. double
  2733. vl_covdet_get_laplacian_peak_threshold (VlCovDet const * self)
  2734. {
  2735. return self->lapPeakThreshold ;
  2736. }
  2737. /** @brief Set the Laplacian peak threshold
  2738. ** @param self object.
  2739. ** @param peakThreshold the Laplacian peak threshold.
  2740. **
  2741. ** The peak threshold must be non-negative.
  2742. **/
  2743. void
  2744. vl_covdet_set_laplacian_peak_threshold (VlCovDet * self, double peakThreshold)
  2745. {
  2746. assert(peakThreshold >= 0) ;
  2747. self->lapPeakThreshold = peakThreshold ;
  2748. }
  2749. /* ---------------------------------------------------------------- */
  2750. /** @brief Get the index of the first octave
  2751. ** @param self object.
  2752. ** @return index of the first octave.
  2753. **/
  2754. vl_index
  2755. vl_covdet_get_first_octave (VlCovDet const * self)
  2756. {
  2757. return self->firstOctave ;
  2758. }
  2759. /** @brief Set the index of the first octave
  2760. ** @param self object.
  2761. ** @param o index of the first octave.
  2762. **
  2763. ** Calling this function resets the detector.
  2764. **/
  2765. void
  2766. vl_covdet_set_first_octave (VlCovDet * self, vl_index o)
  2767. {
  2768. self->firstOctave = o ;
  2769. vl_covdet_reset(self) ;
  2770. }
  2771. /* ---------------------------------------------------------------- */
  2772. /** @brief Get the octave resolution.
  2773. ** @param self object.
  2774. ** @return octave resolution.
  2775. **/
  2776. vl_size
  2777. vl_covdet_get_octave_resolution (VlCovDet const * self)
  2778. {
  2779. return self->octaveResolution ;
  2780. }
  2781. /** @brief Set the octave resolutuon.
  2782. ** @param self object.
  2783. ** @param r octave resoltuion.
  2784. **
  2785. ** Calling this function resets the detector.
  2786. **/
  2787. void
  2788. vl_covdet_set_octave_resolution (VlCovDet * self, vl_size r)
  2789. {
  2790. self->octaveResolution = r ;
  2791. vl_covdet_reset(self) ;
  2792. }
  2793. /* ---------------------------------------------------------------- */
  2794. /** @brief Get whether affine adaptation uses accurate smoothing.
  2795. ** @param self object.
  2796. ** @return @c true if accurate smoothing is used.
  2797. **/
  2798. vl_bool
  2799. vl_covdet_get_aa_accurate_smoothing (VlCovDet const * self)
  2800. {
  2801. return self->aaAccurateSmoothing ;
  2802. }
  2803. /** @brief Set whether affine adaptation uses accurate smoothing.
  2804. ** @param self object.
  2805. ** @param x whether accurate smoothing should be usd.
  2806. **/
  2807. void
  2808. vl_covdet_set_aa_accurate_smoothing (VlCovDet * self, vl_bool x)
  2809. {
  2810. self->aaAccurateSmoothing = x ;
  2811. }
  2812. /* ---------------------------------------------------------------- */
  2813. /** @brief Get the non-extrema suppression threshold
  2814. ** @param self object.
  2815. ** @return threshold.
  2816. **/
  2817. double
  2818. vl_covdet_get_non_extrema_suppression_threshold (VlCovDet const * self)
  2819. {
  2820. return self->nonExtremaSuppression ;
  2821. }
  2822. /** @brief Set the non-extrema suppression threshod
  2823. ** @param self object.
  2824. ** @param x threshold.
  2825. **/
  2826. void
  2827. vl_covdet_set_non_extrema_suppression_threshold (VlCovDet * self, double x)
  2828. {
  2829. self->nonExtremaSuppression = x ;
  2830. }
  2831. /** @brief Get the number of non-extrema suppressed
  2832. ** @param self object.
  2833. ** @return number.
  2834. **/
  2835. vl_size
  2836. vl_covdet_get_num_non_extrema_suppressed (VlCovDet const * self)
  2837. {
  2838. return self->numNonExtremaSuppressed ;
  2839. }
  2840. /* ---------------------------------------------------------------- */
  2841. /** @brief Get number of stored frames
  2842. ** @return number of frames stored in the detector.
  2843. **/
  2844. vl_size
  2845. vl_covdet_get_num_features (VlCovDet const * self)
  2846. {
  2847. return self->numFeatures ;
  2848. }
  2849. /** @brief Get the stored frames
  2850. ** @return frames stored in the detector.
  2851. **/
  2852. void *
  2853. vl_covdet_get_features (VlCovDet * self)
  2854. {
  2855. return self->features ;
  2856. }
  2857. /** @brief Get the Gaussian scale space
  2858. ** @return Gaussian scale space.
  2859. **
  2860. ** A Gaussian scale space exists only after calling ::vl_covdet_put_image.
  2861. ** Otherwise the function returns @c NULL.
  2862. **/
  2863. VlScaleSpace *
  2864. vl_covdet_get_gss (VlCovDet const * self)
  2865. {
  2866. return self->gss ;
  2867. }
  2868. /** @brief Get the cornerness measure scale space
  2869. ** @return cornerness measure scale space.
  2870. **
  2871. ** A cornerness measure scale space exists only after calling
  2872. ** ::vl_covdet_detect. Otherwise the function returns @c NULL.
  2873. **/
  2874. VlScaleSpace *
  2875. vl_covdet_get_css (VlCovDet const * self)
  2876. {
  2877. return self->css ;
  2878. }
  2879. /** @brief Get the number of features found with a certain number of scales
  2880. ** @param self object.
  2881. ** @param numScales length of the histogram (out).
  2882. ** @return histogram.
  2883. **
  2884. ** Calling this function makes sense only after running a detector
  2885. ** that uses the Laplacian as a secondary measure for scale
  2886. ** detection
  2887. **/
  2888. vl_size const *
  2889. vl_covdet_get_laplacian_scales_statistics (VlCovDet const * self,
  2890. vl_size * numScales)
  2891. {
  2892. *numScales = VL_COVDET_MAX_NUM_LAPLACIAN_SCALES ;
  2893. return self->numFeaturesWithNumScales ;
  2894. }