title: OpenCV: Remove the background noise for Tesseract OCR
body: <p>I have a drone FPV video, from which I need extract GPS coordinates. The text is white, but because of bad quality of video it seems gray and light blue. Since the background is changing, I have some problems, because in some frames the background has a totally different and in some frames a similar color to the text one.</p>
  
  <p>Here is 2 original images (frames) from the video:</p>
  
  <ol>
  <li><p>Dark background <img src="https://i.stack.imgur.com/FyjeI.png" alt="Dark background"></p></li>
  <li><p>Light background <img src="https://i.stack.imgur.com/19776.png" alt="Light background"></p></li>
  </ol>
  
  <p>And here is the code that I've found after googling:</p>
  
  <pre class="lang-py prettyprint-override"><code>import numpy as np
  import cv2
  import pytesseract
  
  cap = cv2.VideoCapture('v1.avi')
  
  p = 10000
  while(cap.isOpened()):
  
      ret, frame = cap.read()
  
      img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      img = img[380:460, 220:640]
  
      img = cv2.bilateralFilter(img, 9, 27, 27)
  
      img = cv2.threshold(img, 0, 255,
                          cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
      img = cv2.GaussianBlur(img, (9, 9), 0)
      kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
      img = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
      img = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU)[1]
      img = cv2.dilate(img, kernel)
      img = cv2.threshold(img, 0, 250, cv2.THRESH_BINARY_INV)[1]
  
      cv2.imshow('frame', img)
      cv2.imshow('or', frame)
  
      print('\n==============')
      print(pytesseract.image_to_string(img, config='digits'))
      if cv2.waitKey(50) &amp; 0xFF == ord('q'):
          break
  
  cap.release()
  cv2.destroyAllWindows()
  
  </code></pre>
  
  <p>And also the results:</p>
  
  <ol>
  <li><p>Dark background <img src="https://i.stack.imgur.com/HeBt7.png" alt="Dark background"></p></li>
  <li><p>Light background <img src="https://i.stack.imgur.com/PMlqw.png" alt="Light background"></p></li>
  </ol>
  
  <p>As you can see, in the second case the background isn't clear, there is some noise, and from that image Tesseract doesn't extract the text properly.</p>
  
  <p>EDIT:
  For some reasons I can't share the video I wrote about above, but <a href="https://www.youtube.com/watch?v=TmXh9golh3Y" rel="nofollow noreferrer">here is a similar video from Youtube</a>, and if the text can be extracted from that video, I guess that method will also work for mine or solve many problems at least:</p>
  
  <p><a href="https://www.youtube.com/watch?v=TmXh9golh3Y" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HnrO4.jpg" alt="Similar video from Youtube"></a></p>