shape_transformation.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * shape_context.cpp -- Shape context demo for shape matching
  3. */
  4. #include <iostream>
  5. #include "opencv2/opencv_modules.hpp"
  6. #ifdef HAVE_OPENCV_SHAPE
  7. #include "opencv2/shape.hpp"
  8. #include "opencv2/imgcodecs.hpp"
  9. #include "opencv2/highgui.hpp"
  10. #include "opencv2/imgproc.hpp"
  11. #include "opencv2/features2d.hpp"
  12. #include "opencv2/xfeatures2d.hpp"
  13. #include "opencv2/core/utility.hpp"
  14. #include <string>
  15. using namespace std;
  16. using namespace cv;
  17. using namespace cv::xfeatures2d;
  18. static void help()
  19. {
  20. printf("\nThis program demonstrates how to use common interface for shape transformers\n"
  21. "Call\n"
  22. "shape_transformation [image1] [image2]\n");
  23. }
  24. int main(int argc, char** argv)
  25. {
  26. help();
  27. if (argc < 3)
  28. {
  29. printf("Not enough parameters\n");
  30. return -1;
  31. }
  32. Mat img1 = imread(argv[1], IMREAD_GRAYSCALE);
  33. Mat img2 = imread(argv[2], IMREAD_GRAYSCALE);
  34. if(img1.empty() || img2.empty())
  35. {
  36. printf("Can't read one of the images\n");
  37. return -1;
  38. }
  39. // detecting keypoints & computing descriptors
  40. Ptr<SURF> surf = SURF::create(5000);
  41. vector<KeyPoint> keypoints1, keypoints2;
  42. Mat descriptors1, descriptors2;
  43. surf->detectAndCompute(img1, Mat(), keypoints1, descriptors1);
  44. surf->detectAndCompute(img2, Mat(), keypoints2, descriptors2);
  45. // matching descriptors
  46. BFMatcher matcher(surf->defaultNorm());
  47. vector<DMatch> matches;
  48. matcher.match(descriptors1, descriptors2, matches);
  49. // drawing the results
  50. namedWindow("matches", 1);
  51. Mat img_matches;
  52. drawMatches(img1, keypoints1, img2, keypoints2, matches, img_matches);
  53. imshow("matches", img_matches);
  54. // extract points
  55. vector<Point2f> pts1, pts2;
  56. for (size_t ii=0; ii<keypoints1.size(); ii++)
  57. pts1.push_back( keypoints1[ii].pt );
  58. for (size_t ii=0; ii<keypoints2.size(); ii++)
  59. pts2.push_back( keypoints2[ii].pt );
  60. // Apply TPS
  61. Ptr<ThinPlateSplineShapeTransformer> mytps = createThinPlateSplineShapeTransformer(25000); //TPS with a relaxed constraint
  62. mytps->estimateTransformation(pts1, pts2, matches);
  63. mytps->warpImage(img2, img2);
  64. imshow("Tranformed", img2);
  65. waitKey(0);
  66. return 0;
  67. }
  68. #else
  69. int main()
  70. {
  71. std::cerr << "OpenCV was built without shape module" << std::endl;
  72. return 0;
  73. }
  74. #endif // HAVE_OPENCV_SHAPE