title: OpenCV binary adaptive threshold OCR
body: <p>I need to convert some images to binary for OCR.</p>
  <p>Here are the functions I am using:</p>
  <pre><code>Mat binarize(Mat &amp; Img, Mat&amp; res, float blocksize, bool inverse)
  {
      Img.convertTo(Img,CV_32FC1,1.0/255.0);
      CalcBlockMeanVariance(Img,res, blocksize, inverse);
      res=1.0-res;
      res=Img+res;
      if (inverse) {
          cv::threshold(res,res,0.85,1,cv::THRESH_BINARY_INV);
      } else {
          cv::threshold(res,res,0.85,1,cv::THRESH_BINARY);
      }
      cv::resize(res,res,cv::Size(res.cols/2,res.rows/2));
      
      return res;
  }
  </code></pre>
  <p>Where <code>CalcBlockMeanVariance</code>:</p>
  <pre><code>void CalcBlockMeanVariance(Mat&amp; Img,Mat&amp; Res,float blockSide, bool inverse) //21 blockSide - the parameter (set greater for larger font on image)
  {
      Mat I;
      Img.convertTo(I,CV_32FC1);
      Res=Mat::zeros(Img.rows/blockSide,Img.cols/blockSide,CV_32FC1);
      Mat inpaintmask;
      Mat patch;
      Mat smallImg;
      Scalar m,s;
      
      for(int i=0;i&lt;Img.rows-blockSide;i+=blockSide)
      {
          for (int j=0;j&lt;Img.cols-blockSide;j+=blockSide)
          {
              patch=I(Range(i,i+blockSide+1),Range(j,j+blockSide+1));
              cv::meanStdDev(patch,m,s);
              if(s[0]&gt;0.01) // Thresholding parameter (set smaller for lower contrast image)
              {
                  Res.at&lt;float&gt;(i/blockSide,j/blockSide)=m[0];
              }else
              {
                  Res.at&lt;float&gt;(i/blockSide,j/blockSide)=0;
              }
          }
      }
      
      cv::resize(I,smallImg,Res.size());
      
      if (inverse) {
          cv::threshold(Res,inpaintmask,0.02,1.0,cv::THRESH_BINARY_INV);
      } else {
          cv::threshold(Res,inpaintmask,0.02,1.0,cv::THRESH_BINARY);
      }
      
      
      Mat inpainted;
      smallImg.convertTo(smallImg,CV_8UC1,255);
      
      inpaintmask.convertTo(inpaintmask,CV_8UC1);
      inpaint(smallImg, inpaintmask, inpainted, 5, INPAINT_TELEA);
      
      cv::resize(inpainted,Res,Img.size());
      Res.convertTo(Res,CV_32FC1,1.0/255.0);
      
  }
  </code></pre>
  <p>When passing in <code>1</code> to <code>CalcBlockMeanVariance</code> as the <code>blockSide</code> I get this result, I have tried to raise the <code>blockSide</code> but it only results in worse results.</p>
  <p>Before:</p>
  <p><img src="https://i.stack.imgur.com/6dHN1.png" alt="enter image description here" /></p>
  <p>After:</p>
  <p><img src="https://i.stack.imgur.com/TI1qR.png" alt="enter image description here" /></p>
  <p>Can anyone suggest a different method for converting this image to binary as prep for OCR?</p>
  <p>Thanks.</p>