information_flow_matting.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // This file is part of OpenCV project.
  2. // It is subject to the license terms in the LICENSE file found in the top-level directory
  3. // of this distribution and at http://opencv.org/license.html.
  4. // Include relevant headers
  5. #include <iostream>
  6. #include "opencv2/highgui.hpp"
  7. #include <opencv2/core.hpp>
  8. #include <opencv2/imgproc.hpp>
  9. #include <opencv2/alphamat.hpp>
  10. // Set namespaces
  11. using namespace std;
  12. using namespace cv;
  13. using namespace cv::alphamat;
  14. // Set the usage parameter names
  15. const char* keys =
  16. "{img || input image name}"
  17. "{tri || input trimap image name}"
  18. "{out || output image name}"
  19. "{help h || print help message}"
  20. ;
  21. int main(int argc, char* argv[])
  22. {
  23. CommandLineParser parser(argc, argv, keys);
  24. parser.about("This sample demonstrates Information Flow Alpha Matting");
  25. if (parser.has("help"))
  26. {
  27. parser.printMessage();
  28. return 0;
  29. }
  30. // Read the paths to the input image, input trimap and the location of the output image.
  31. string img_path = parser.get<std::string>("img");
  32. string trimap_path = parser.get<std::string>("tri");
  33. string result_path = parser.get<std::string>("out");
  34. // Make sure the user inputs paths to the input image and trimap
  35. if (!parser.check()
  36. || img_path.empty() || trimap_path.empty())
  37. {
  38. parser.printMessage();
  39. parser.printErrors();
  40. return 1;
  41. }
  42. Mat image, tmap;
  43. // Read the input image
  44. image = imread(img_path, IMREAD_COLOR);
  45. if (image.empty())
  46. {
  47. printf("Cannot read image file: '%s'\n", img_path.c_str());
  48. return 1;
  49. }
  50. // Read the trimap
  51. tmap = imread(trimap_path, IMREAD_GRAYSCALE);
  52. if (tmap.empty())
  53. {
  54. printf("Cannot read trimap file: '%s'\n", trimap_path.c_str());
  55. return 1;
  56. }
  57. Mat result;
  58. // Perform information flow alpha matting
  59. infoFlow(image, tmap, result);
  60. if (result_path.empty())
  61. {
  62. // Show the alpha matte if a result filepath is not provided.
  63. namedWindow("result alpha matte", WINDOW_NORMAL);
  64. imshow("result alpha matte", result);
  65. waitKey(0);
  66. }
  67. else
  68. {
  69. // Save the alphamatte
  70. imwrite(result_path, result);
  71. printf("Result saved: '%s'\n", result_path.c_str());
  72. }
  73. return 0;
  74. }