The background of the image is the problem. You can omit by selecting a height-range

For example: If you select the height-range between: h/4 - (3*h)/4, result will be: (image is resized due to exceeding 2MiB.)

When you read:

Nikhil Suthar
Regional Coordinator - OSD

Email | Mob. |

Govt. Technical High School Campus, Near Aurobindo
Ashram Dandia Bazar, Vadodara - 390001, Gujarat, India
www.gtu.ac.in | www.gtuinnovationcouncil.ac.in

Code:


import cv2
from pytesseract import image_to_string

img = cv2.imread("Oa9svHu.jpeg")
gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
(h, w) = gry.shape[:2]
gry = gry[int(h/4):int((3*h)/4), 0:w]
txt = image_to_string(gry)
print(txt.strip())
cv2.imshow("gry", gry)
cv2.waitKey(0)
Answer from Ahmet on Stack Overflow
Top answer
1 of 1
5

Here's a simple approach

  • Convert image to grayscale
  • Otsu's threshold
  • Dilate to connect contours
  • Find contours and extract ROI for each word
  • Perform OCR and remove word

After converting to grayscale, we Otsu's threshold to obtain a binary image

Next we invert the image and dilate to form a single contour for each word

From here we find contours and extract the ROI for each word. Here's the detected ROIs

We throw each ROI into Pytesseract OCR. If the OCR result is a word we want to remove, we simply "delete" the word by filling in the ROI with white and replace it in the original image


With

words_to_remove = ['on', 'you', 'crazy']

The result is

Similarly with

words_to_remove = ['on', 'you', 'shine', 'diamond']

The result is

Finally with

words_to_remove = ['on', 'you', 'crazy', 'diamond']

import cv2
import pytesseract

words_to_remove = ['on', 'you', 'crazy', 'diamond']
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

image = cv2.imread("1.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
inverted_thresh = 255 - thresh
dilate = cv2.dilate(inverted_thresh, kernel, iterations=4)

cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    ROI = thresh[y:y+h, x:x+w]
    data = pytesseract.image_to_string(ROI, lang='eng',config='--psm 6').lower()
    if data in words_to_remove:
        image[y:y+h, x:x+w] = [255,255,255]

cv2.imshow("thresh", thresh)
cv2.imshow("dilate", dilate)
cv2.imshow("image", image)
cv2.waitKey(0)
Discussions

python - Correctly extract text from image using Tesseract OCR - Stack Overflow
This now has all the background artifacts removed but it is now reading the first letter I as 1 and the 9 is read as 3 ... I have tesseract.js working locally, and I cannot get it. Best accuracy outputs IEM-9U, every time. I reduced brightness, upped contrast slightly and a hard sharpen. Image. Now, it's IBM-9U, consistently. I've pulled way worse text... More on stackoverflow.com
🌐 stackoverflow.com
python - How to remove text from the sketched image - Stack Overflow
I have some sketched images where the images contain text captions. I am trying to remove those caption. I am using this code: import cv2 import pytesseract pytesseract.pytesseract.tesseract_cmd = r& More on stackoverflow.com
🌐 stackoverflow.com
Improve Tesseract OCR results by removing special characters - Stack Overflow
I am doing the tesseract conversion on some pdf, image, tiff files saved in my db. But while doing it I am getting lots of garbage text output from various files. For example, in this case the imag... More on stackoverflow.com
🌐 stackoverflow.com
python - How to clean text in image for Tesseract to read - Stack Overflow
I'm using pytesseract to read text from images, but the text is rotated and there is a light source that creates shadows. The code rotates the image half a degree each time expecting a match but some of the images I provide (all of them are quite similar) don't even output any text when Tesseract ... More on stackoverflow.com
🌐 stackoverflow.com
August 21, 2019
People also ask

What is Tesseract OCR?

Tesseract OCR is an open source engine for recognizing text from images and scanned documents. Developed by Hewlett-Packard and now sponsored by Google, it supports more than 100 languages and various text styles.

🌐
nutrient.io
nutrient.io › blog › sdk › how to use tesseract ocr in python
Python OCR with pytesseract: Extract text from images using Tesseract ...
What are the limitations of Tesseract OCR?

Tesseract’s limitations include varying accuracy based on image quality, difficulty with non-standard fonts, and limited support for complex layouts and languages. It also lacks built-in image preprocessing.

🌐
nutrient.io
nutrient.io › blog › sdk › how to use tesseract ocr in python
Python OCR with pytesseract: Extract text from images using Tesseract ...
Can Tesseract OCR handle multiple languages?

Yes. Tesseract supports multiple languages. Use a plus sign (+) in the configuration string, like -l eng+fra for English and French.

🌐
nutrient.io
nutrient.io › blog › sdk › how to use tesseract ocr in python
Python OCR with pytesseract: Extract text from images using Tesseract ...
🌐
Google Groups
groups.google.com › g › tesseract-ocr › c › ZO7Bd-rBNl0
need help removing garbage characters from my OCR
I suspect you'd get better results by feeding each square separately, though, as you can then use PSM_SINGLE_CHAR, and Tesseract has a better chance of taking the number in the corner into account. As Paul suggested, though, binarisation may be an issue too. You can check how well it does by using the tessedit_write_images config setting; see https://code.google.com/p/tesseract-ocr/wiki/ImproveQuality#Image_processing Nick
🌐
Stack Overflow
stackoverflow.com › questions › 78450023 › correctly-extract-text-from-image-using-tesseract-ocr
python - Correctly extract text from image using Tesseract OCR - Stack Overflow
import cv2 import pytesseract img = cv2.imread('16M.png',cv2.IMREAD_UNCHANGED) (thresh, blackAndWhiteImage) = cv2.threshold(img, 63, 255, cv2.THRESH_BINARY) # resize image scale_percent = 4 # percent of original size width = int(blackAndWhiteImage.shape[1] * scale_percent / 100) height = int(blackAndWhiteImage.shape[0] * scale_percent / 100) dim = (width, height) resized = cv2.resize(blackAndWhiteImage, dim, interpolation = cv2.INTER_AREA) # OCR resized Black & White image pytesseract.pytesseract.tesseract_cmd=r'C:\Program Files\Tesseract-OCR\tesseract.exe' # Remove 1 from filter, than you will get I instead custom_config = r'--psm 6 --oem 3 -c tessedit_char_whitelist=-.ABCDEFTGHIJKLMNOPQRSTUVWXYZ0123456789' tex = pytesseract.image_to_string(resized, config=custom_config) print(tex) # Display cropped image cv2.imshow("Image", resized) cv2.waitKey(0) cv2.destroyAllWindows()
🌐
Tesseract OCR
tesseract-ocr.github.io › tessdoc › ImproveQuality.html
Improving the quality of the output - Tesseract documentation
It is known tesseract has a problem to recognize text/data from tables (see issues tracker) without custom segmentation/layout analysis. You can try to use/test Sintun proposal or get some ideas from Text Extraction from a Table Image, using PyTesseract and OpenCV/code for Text-Extraction-Table-Image
Top answer
1 of 2
3

The cv2 pre-processing is unecessary here, tesseract is able to find the text on its own. See the example below, commented inline:

results = pytesseract.image_to_data('1.png', config='--psm 11', output_type='dict')

for i in range(len(results["text"])):
    # extract the bounding box coordinates of the text region from
    # the current result
    x = results["left"][i]
    y = results["top"][i]
    w = results["width"][i]
    h = results["height"][i]
    # Extract the confidence of the text
    conf = int(results["conf"][i])
    
    if conf > 60: # adjust to your liking
        # Cover the text with a white rectangle
        cv2.rectangle(image, (x, y), (x + w, y + h), (255, 255, 255), -1)

Detected text on the left, cleaned image on the right:

2 of 2
3

Another option, without using Tesseract. Just use the area of the contours to filter the smaller ones by covering them with white-filled rectangles:

# Imports
import cv2
import numpy as np

# Read image
imagePath = "C://opencvImages//"
inputImage = cv2.imread(imagePath+"0enxN.png")

# Convert BGR to grayscale:
binaryImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)
# Invert image:
binaryImage = 255 - binaryImage

# Find the external contours on the binary image:
contours, hierarchy = cv2.findContours(binaryImage, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Invert image:
binaryImage = 255 - binaryImage

# Look for the bounding boxes:
for _, c in enumerate(contours):

    # Get the contour's bounding rectangle:
    boundRect = cv2.boundingRect(c)

    # Get the dimensions of the bounding rect:
    rectX = boundRect[0]
    rectY = boundRect[1]
    rectWidth = boundRect[2]
    rectHeight = boundRect[3]

    # Get Bounding Rectangle Area:
    rectArea = rectWidth * rectHeight
    # Set minimum area threshold:
    minArea = 1000

    # Check for minimum area:
    if rectArea < minArea:
        # Draw white rectangle to cover small contour:
        cv2.rectangle(binaryImage, (rectX, rectY), (rectX + rectWidth, rectY + rectHeight),
                      (255, 255, 255), -1)
        cv2.imshow("Binary Mask", binaryImage)
        cv2.waitKey(0)

This produces:

🌐
GitHub
github.com › iuliaturc › detextify
GitHub - iuliaturc/detextify: Remove text from AI-generated images · GitHub
Detextify runs text detection on your image, masks the text boxes, and in-paints the masked regions until your image is text-free. Detextify can be run entirely on your local machine (using Tesseract for text detection and Stable Diffusion for in-painting), or can call existing APIs (Azure for text detection and OpenAI or Replicate for in-painting).
Starred by 311 users
Forked by 26 users
Languages   Python 99.8% | Shell 0.2%
Find elsewhere
🌐
Nutrient
nutrient.io › blog › sdk › how to use tesseract ocr in python
Python OCR with pytesseract: Extract text from images using Tesseract (2026)
3 weeks ago - Extract text, tables, and key-value pairs from any document · Structured output with per-field confidence scores through the Nutrient Data Extraction API. ... Install pytesseract and the Tesseract engine. Then call pytesseract.image_to_str...
🌐
Google Groups
groups.google.com › g › tesseract-ocr › c › Sk6cLQ7qT6w
Get Tesseract ocr to ignore or replace images with whitespace
I recently added this feature to OpenOCR -- the idea is that it can remove the non-text elements from an image, leaving only the text.
🌐
Medium
aicha-fatrah.medium.com › improve-the-quality-of-your-ocr-information-extraction-ebc93d905ac4
Improve the quality of your OCR information extraction | by Aicha Fatrah | Medium
March 21, 2022 - So the best practice is to remove the alpha-channel before passing the image to Tesseract. You can use ImageMagick to do so. ... I reviewed some code implementations of Tesseract and I noticed that many developers do not exploit some Tesseract options that can change the output. So I thought that I should mention two options that I use a lot. You can check all the options with --help-extra . By default, Tesseract expects a page of text when it segments an image.
🌐
Stack Overflow
stackoverflow.com › questions › 43603395 › improve-tesseract-ocr-results-by-removing-special-characters
Improve Tesseract OCR results by removing special characters - Stack Overflow
"tessedit_char_whitelist abcdefghijklmnopqrstuvwxyz" will include only the alphabets and then it will ignore the number ? and on this "tesseract input.tif output nobatch letters " what does "nobatch" referring to ? 2017-04-26T07:47:58.813Z+00:00 ... after doing this I am getting this he fhawfyhftiwlwwfuisipgkggfawfarwtwofrrletitwtfilfmjafgurrwsnnve mania a i v a an izromrseaver medical internal tilted sos min seaa oslaelaoie urea arses ptoosloos numbers got disappeared. I also want the number what can be done and also need to remove the unwanted text like he fhawfyhftiwlwwfuisipgkggfawfarwtwofrrletitwtfilfmjafgurrwsnnve mania a i v a an from starting.
🌐
CRAN
cran.r-project.org › web › packages › tesseract › vignettes › intro.html
tesseract package in R - CRAN - R Project
But if you can get your input images to reasonable quality, Tesseract can often help to extract most of the text from the image.
🌐
Opcito Technologies
opcito.com › blogs › extracting-text-from-images-with-tesseract-ocr-opencv-and-python
Text extraction with Tesseract, OpenCV, Python
May 21, 2020 - By default, Tesseract considers the input image as a page of text in segments. You can configure Tesseract’s different segmentations if you are interested in capturing a small region of text from the image. You can do it by assigning --psm mode to it. Tesseract fully automates the page segmentation, but it does not perform orientation and script detection.
🌐
Stack Overflow
stackoverflow.com › questions › 57582468 › how-to-clean-text-in-image-for-tesseract-to-read
python - How to clean text in image for Tesseract to read - Stack Overflow
August 21, 2019 - Copypytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' image = Image.open("Image.png") converter = ImageEnhance.Color(image) imagedesat = converter.enhance(0) imagedesat = imagedesat.filter(ImageFilter.SHARPEN) cropped = imagedesat.crop((0,80,211,186)) text = pytesseract.image_to_string(cropped, lang='eng') cropped.save('Result.png') rotated = cropped.rotate(0) while text == "": rotated = rotated.rotate(-0.5) text = pytesseract.image_to_string(rotated, lang='eng') print(text)
Top answer
1 of 7
64

Here's a simple approach using OpenCV and Pytesseract OCR. To perform OCR on an image, its important to preprocess the image. The idea is to obtain a processed image where the text to extract is in black with the background in white. To do this, we can convert to grayscale, apply a slight Gaussian blur, then Otsu's threshold to obtain a binary image. From here, we can apply morphological operations to remove noise. Finally we invert the image. We perform text extraction using the --psm 6 configuration option to assume a single uniform block of text. Take a look here for more options.


Here's a visualization of the image processing pipeline:

Input image

Convert to grayscale -> Gaussian blur -> Otsu's threshold

Notice how there are tiny specs of noise, to remove them we can perform morphological operations

Finally we invert the image

Result from Pytesseract OCR

2HHH

Code

import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

# Grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Morph open to remove noise and invert image
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)
invert = 255 - opening

# Perform text extraction
data = pytesseract.image_to_string(invert, lang='eng', config='--psm 6')
print(data)

cv2.imshow('thresh', thresh)
cv2.imshow('opening', opening)
cv2.imshow('invert', invert)
cv2.waitKey()
2 of 7
40

Here is my solution:

import pytesseract
from PIL import Image, ImageEnhance, ImageFilter

im = Image.open("temp.jpg") # the second one 
im = im.filter(ImageFilter.MedianFilter())
enhancer = ImageEnhance.Contrast(im)
im = enhancer.enhance(2)
im = im.convert('1')
im.save('temp2.jpg')
text = pytesseract.image_to_string(Image.open('temp2.jpg'))
print(text)
🌐
Analytics Vidhya
analyticsvidhya.com › home › optical character recognition(ocr): tesseract, opencv, and python
Optical Character Recognition(OCR): Tesseract, OpenCV, and Python
February 26, 2024 - Optical Character Recognition (OCR) is a technique to extract text from printed or scanned photos, handwritten text images and convert them into a digital format that can be editable and searchable. OCR has plenty of applications in today’s business. A few of them are listed below: ... In this article, we will focus on Tesseract OCR.
🌐
Automate the Boring Stuff
automatetheboringstuff.com › 3e › chapter22.html
Chapter 22 - Recognizing Text in Images, Automate the Boring Stuff with Python, 3rd Ed
To install the language packs for every language, run sudo apt install tesseract-ocr-all from the terminal. To install just the language packs you want, replace all with a three-character ISO 639 language code, such as fra for French, deu for German, or jpn for Japanese. After installing the Tesseract OCR engine, you can install the latest version of PyTesseract by following the instructions in Appendix A. PyTesseract also installs the Pillow image library. Using PyTesseract and the Pillow image library, you can extract text from an image in four lines of code.
🌐
Nanonets
nanonets.com › nanonets ocr › ocr buyer's guide › python ocr tutorial: tesseract, pytesseract, and opencv
Python OCR Tutorial: Tesseract, Pytesseract, and OpenCV
September 9, 2025 - Try out the Nanonets' free online OCR tool to convert images and OCR your PDFs. Tesseract is an open-source text recognition (OCR) Engine, available under the Apache 2.0 license. It can be used directly, or (for programmers) using an API to extract printed text from images.
🌐
Pysource
pysource.com › home › blog › text recognition (ocr) with tesseract and opencv
Text recognition (OCR) with Tesseract and Opencv - Pysource
September 20, 2024 - Before proceeding with the installation of Tesseract, it’s important to understand all the tools that we are going to use and the purpose of each of them. ... Python and Opencv: we will use the python programming language and Opencv to load the image, and do some image preprocessing (for example remove the areas where there is no text, remove some noise, apply some image filter to make the text more readable).