textdetection_swt.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Sample code which demonstrates the working of
  2. // stroke width transform in the text module of OpenCV
  3. #include <opencv2/text.hpp>
  4. #include <opencv2/highgui.hpp>
  5. #include <opencv2/imgproc.hpp>
  6. #include <opencv2/imgcodecs.hpp>
  7. #include <iostream>
  8. #include <fstream>
  9. #include <vector>
  10. #include <string>
  11. using namespace std;
  12. using namespace cv;
  13. static void help(const CommandLineParser& cmd, const string& errorMessage)
  14. {
  15. cout << errorMessage << endl;
  16. cout << "Avaible options:" << endl;
  17. cmd.printMessage();
  18. }
  19. static bool fileExists (const string& filename)
  20. {
  21. ifstream f(filename.c_str());
  22. return f.good();
  23. }
  24. int main(int argc, const char * argv[])
  25. {
  26. const char* keys =
  27. "{help h usage ? |false | print this message }"
  28. "{@image | | path to image }"
  29. "{@darkOnLight |false | indicates whether text to be extracted is dark on a light brackground. Defaults to false. }"
  30. ;
  31. CommandLineParser cmd(argc, argv, keys);
  32. if(cmd.get<bool>("help"))
  33. {
  34. help(cmd, "Usage: ./textdetection_swt [options] \nExample: ./textdetection_swt scenetext_segmented_word03.jpg true");
  35. return EXIT_FAILURE;
  36. }
  37. string filepath = cmd.get<string>("@image");
  38. if (!fileExists(filepath)) {
  39. help(cmd, "ERROR: Could not find the image file. Please check the path.");
  40. return EXIT_FAILURE;
  41. }
  42. bool dark_on_light = cmd.get<bool>("@darkOnLight");
  43. Mat image = imread(filepath, IMREAD_COLOR);
  44. if (image.empty())
  45. {
  46. help(cmd, "ERROR: Could not load the image file");
  47. return EXIT_FAILURE;
  48. }
  49. cout << "Starting SWT Text Detection Demo with dark_on_light variable set to " << dark_on_light << endl;
  50. imshow("Input Image", image);
  51. waitKey(1);
  52. vector<cv::Rect> components;
  53. Mat out;
  54. vector<cv::Rect> regions;
  55. cv::text::detectTextSWT(image, components, dark_on_light, out, regions);
  56. imshow ("Letter Candidates", out);
  57. waitKey(1);
  58. cout << components.size() << " letter candidates found." << endl;
  59. Mat image_copy = image.clone();
  60. for (unsigned int i = 0; i < regions.size(); i++) {
  61. rectangle(image_copy, regions[i], cv::Scalar(0, 0, 0), 3);
  62. }
  63. cout << regions.size() << " chains were obtained after merging suitable pairs" << endl;
  64. cout << "Recognition finished. Press any key to exit..." << endl;
  65. imshow ("Chains After Merging", image_copy);
  66. waitKey();
  67. return 0;
  68. }