text_skewness_correction.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. This tutorial demonstrates how to correct the skewness in a text.
  3. The program takes as input a skewed source image and shows non skewed text.
  4. */
  5. #include <opencv2/core.hpp>
  6. #include <opencv2/imgcodecs.hpp>
  7. #include <opencv2/highgui.hpp>
  8. #include <opencv2/imgproc.hpp>
  9. #include <iostream>
  10. #include <iomanip>
  11. #include <string>
  12. using namespace cv;
  13. using namespace std;
  14. int main( int argc, char** argv )
  15. {
  16. CommandLineParser parser(argc, argv, "{@input | imageTextR.png | input image}");
  17. // Load image from the disk
  18. Mat image = imread( samples::findFile( parser.get<String>("@input") ), IMREAD_COLOR);
  19. if (image.empty())
  20. {
  21. cout << "Cannot load the image " + parser.get<String>("@input") << endl;
  22. return -1;
  23. }
  24. Mat gray;
  25. cvtColor(image, gray, COLOR_BGR2GRAY);
  26. //Threshold the image, setting all foreground pixels to 255 and all background pixels to 0
  27. Mat thresh;
  28. threshold(gray, thresh, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
  29. // Applying erode filter to remove random noise
  30. int erosion_size = 1;
  31. Mat element = getStructuringElement( MORPH_RECT, Size(2*erosion_size+1, 2*erosion_size+1), Point(erosion_size, erosion_size) );
  32. erode(thresh, thresh, element);
  33. cv::Mat coords;
  34. findNonZero(thresh, coords);
  35. RotatedRect box = minAreaRect(coords);
  36. float angle = box.angle;
  37. // The cv::minAreaRect function returns values in the range [-90, 0)
  38. // if the angle is less than -45 we need to add 90 to it
  39. if (angle < -45.0f)
  40. {
  41. angle = (90.0f + angle);
  42. }
  43. //Obtaining the rotation matrix
  44. Point2f center((image.cols) / 2.0f, (image.rows) / 2.0f);
  45. Mat M = getRotationMatrix2D(center, angle, 1.0f);
  46. Mat rotated;
  47. // Rotating the image by required angle
  48. stringstream angle_to_str;
  49. angle_to_str << fixed << setprecision(2) << angle;
  50. warpAffine(image, rotated, M, image.size(), INTER_CUBIC, BORDER_REPLICATE);
  51. putText(rotated, "Angle " + angle_to_str.str() + " degrees", Point(10, 30), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0, 0, 255), 2);
  52. cout << "[INFO] angle: " << angle_to_str.str() << endl;
  53. //Show the image
  54. imshow("Input", image);
  55. imshow("Rotated", rotated);
  56. waitKey(0);
  57. return 0;
  58. }