Read Text From Image using Python, OpenCv and pytesseract Part1

Abhishek Kumar Gupta
3 min readMay 6, 2024

--

This time I am developing a module for the Retail Sales for my own family business (Motorbikes Garage). Where I want to reduce the mismatch of price of product when the price of product has been changed (which caused the loss of money to vender as maximum time vendor will not look into price whether it has been updated or not). So to overcome of this problem I think if anyway I can capture the MRP of the product from the packet from its uploaded image instead of writing it manually. This is my start of the module and for this I am using opencv and pytesseract.

Before start work on this module firstly install the below dependency.

Dependencies

  1. Install openCv from following document: https://pypi.org/project/opencv-python/

2. Install the pytesseract from the following link(https://github.com/UB-Mannheim/tesseract/wiki).

Code Snippet for Reading the Packet Text:

import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = (
r"D:\\softwareNdPrograms\\Tesseract-OCR\\tesseract.exe"
)

img = cv2.imread('C:\\Users\\Ambika\\Downloads\\tvs\\part2.jpeg', cv2.IMREAD_GRAYSCALE)
scale = 110
width = int(img.shape[1] * scale / 100)
height = int(img.shape[0])
dim = (width, height)
resized = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)

(thresh, im_bw) = cv2.threshold(resized, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
thresh = 127
im_bw = cv2.threshold(resized, thresh, 255, cv2.THRESH_BINARY)[1]
cv2.imwrite('C:\\Users\\Downloads\\tvs\\resized_img.png', im_bw)
print(pytesseract.image_to_string('C:\\Users\\Downloads\\tvs\\resized_img.png'))

Explanation: From the above code you can see I have kept the height constant and increase the width of the image by 10% and then I converted the Gray Scale image into black and white. Now I am able to capture text from around 85% and I maximum case I am getting the correct MRP of the Produce.

part2.jpeg original image:

Black and White Image After applying scaling by 10% increase in width and keeping height constant.

Output at Terminal:

Output at Terminal

Thank you for going through the article. If you are looking for any assistance related to Html, css, React, React Native, Next.js, Node.js, GraphQl, Python, Flask, Panda. Please let me know. I will be glad to help you.
To tell us about your concern please fill the form: https://docs.google.com/forms/d/1uh343ab8uwVhCpozi_etFyV67f6zVoIiMlrYKLwOgnE/prefill or visit and mail your concern by visiting my blog page.

--

--

Abhishek Kumar Gupta
Abhishek Kumar Gupta

Written by Abhishek Kumar Gupta

Web and Native Mobile App Developer.

No responses yet