title: Calculating skew of text OpenCV
body: <p>I am trying to calculate the skew of text in an image so I can correct it for the best OCR results. </p>
  
  <p>Currently this is the function I am using:</p>
  
  <pre><code>double compute_skew(Mat &amp;img)
  {
  
      // Binarize
      cv::threshold(img, img, 225, 255, cv::THRESH_BINARY);
  
      // Invert colors
      cv::bitwise_not(img, img);
  
      cv::Mat element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 3));
      cv::erode(img, img, element);
  
      std::vector&lt;cv::Point&gt; points;
      cv::Mat_&lt;uchar&gt;::iterator it = img.begin&lt;uchar&gt;();
      cv::Mat_&lt;uchar&gt;::iterator end = img.end&lt;uchar&gt;();
      for (; it != end; ++it)
          if (*it)
              points.push_back(it.pos());
  
      cv::RotatedRect box = cv::minAreaRect(cv::Mat(points));
  
      double angle = box.angle;
      if (angle &lt; -45.)
          angle += 90.;
  
      cv::Point2f vertices[4];
      box.points(vertices);
      for(int i = 0; i &lt; 4; ++i)
          cv::line(img, vertices[i], vertices[(i + 1) % 4], cv::Scalar(255, 0, 0), 1, CV_AA);
  
      return angle;
  }
  </code></pre>
  
  <p>When I look at then angle in debug I get <code>0.000000</code>
  <img src="https://i.stack.imgur.com/B6PSV.png" alt="enter image description here"></p>
  
  <p>However when I give it this image I get proper results of a skew of about 16 degrees:</p>
  
  <p><img src="https://i.stack.imgur.com/ouy3d.jpg" alt="enter image description here"></p>
  
  <p>How can I properly detect the skew in the first image?</p>