title: Image preprocessing with OpenCV before doing character recognition (tesseract)
body: <p>I'm trying to develop simple PC application for license plate recognition (Java + OpenCV + Tess4j). Images aren't really good (in further they will be good). I want to preprocess image for tesseract, and I'm stuck on detection of license plate (rectangle detection).</p>
  
  <p>My steps:</p>
  
  <p>1) Source Image</p>
  
  <p><a href="https://i.stack.imgur.com/MHy0N.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/MHy0N.jpg" alt="True Image"></a></p>
  
  <pre><code>Mat img = new Mat();
  img = Imgcodecs.imread("sample_photo.jpg"); 
  Imgcodecs.imwrite("preprocess/True_Image.png", img);
  </code></pre>
  
  <p>2) Gray Scale</p>
  
  <pre><code>Mat imgGray = new Mat();
  Imgproc.cvtColor(img, imgGray, Imgproc.COLOR_BGR2GRAY);
  Imgcodecs.imwrite("preprocess/Gray.png", imgGray);
  </code></pre>
  
  <p>3) Gaussian Blur</p>
  
  <pre><code>Mat imgGaussianBlur = new Mat(); 
  Imgproc.GaussianBlur(imgGray,imgGaussianBlur,new Size(3, 3),0);
  Imgcodecs.imwrite("preprocess/gaussian_blur.png", imgGaussianBlur);  
  </code></pre>
  
  <p>4) Adaptive Threshold</p>
  
  <pre><code>Mat imgAdaptiveThreshold = new Mat();
  Imgproc.adaptiveThreshold(imgGaussianBlur, imgAdaptiveThreshold, 255, CV_ADAPTIVE_THRESH_MEAN_C ,CV_THRESH_BINARY, 99, 4);
  Imgcodecs.imwrite("preprocess/adaptive_threshold.png", imgAdaptiveThreshold);
  </code></pre>
  
  <p>Here should be 5th step, which is detection of plate region (probably even without deskewing for now).</p>
  
  <p>I croped needed region from image (after 4th step) with Paint, and got:</p>
  
  <p><a href="https://i.stack.imgur.com/6lc9H.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6lc9H.png" alt="plate region"></a></p>
  
  <p>Then I did OCR (via tesseract, tess4j):</p>
  
  <pre><code>File imageFile = new File("preprocess/adaptive_threshold_AFTER_PAINT.png");
  ITesseract instance = new Tesseract();
  instance.setLanguage("eng");
  instance.setTessVariable("tessedit_char_whitelist", "acekopxyABCEHKMOPTXY0123456789");
  String result = instance.doOCR(imageFile); 
  System.out.println(result);
  </code></pre>
  
  <p>and got (good enough?) result - "Y841ox EH" (almost true)</p>
  
  <p>How can I detect and crop plate region after 4th step? Have I to make some changes (improvements) in 1-4 steps? Would like to see some example implemented via Java + OpenCV (not JavaCV). <br/>
  Thanks in advance.</p>
  
  <p><strong>EDIT</strong> (thanks to @Abdul Fatir's answer)
  Well, I provide working (for me atleast) code sample (Netbeans+Java+OpenCV+Tess4j) for those who interested in this question. Code is not the best, but I made it just for studying. <br>
  <a href="http://pastebin.com/H46wuXWn" rel="noreferrer">http://pastebin.com/H46wuXWn</a> (do not forget to put <em>tessdata</em> folder into your project folder)</p>