Detect and fix text skew by rotating image

Issue

Is there a way (using something like OpenCV) to detect text skew and correct it by rotating the image? Pretty much like this?

enter image description here

enter image description here

Rotating an image seems easy enough if you know the angle, but for the images I’m processing, I wont…it will need to be detected somehow.

Solution

Based on your above comment, here is the code based on the tutorial here, working fine for the above image,

Source

enter image description here

Rotated

enter image description here

 Mat src=imread("text.png",0);
 Mat thr,dst;
 threshold(src,thr,200,255,THRESH_BINARY_INV);
 imshow("thr",thr);

  std::vector<cv::Point> points;
  cv::Mat_<uchar>::iterator it = thr.begin<uchar>();
  cv::Mat_<uchar>::iterator end = thr.end<uchar>();
  for (; it != end; ++it)
    if (*it)
      points.push_back(it.pos());

  cv::RotatedRect box = cv::minAreaRect(cv::Mat(points));
  cv::Mat rot_mat = cv::getRotationMatrix2D(box.center, box.angle, 1);

  //cv::Mat rotated(src.size(),src.type(),Scalar(255,255,255));
  Mat rotated;
  cv::warpAffine(src, rotated, rot_mat, src.size(), cv::INTER_CUBIC);
 imshow("rotated",rotated);

Edit:

Also see the answer here , might be helpful.

Answered By – Haris

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.