Skip to content

Instantly share code, notes, and snippets.

@akash-ch2812
Last active May 4, 2023 10:27
Show Gist options
  • Save akash-ch2812/ffcf6ce7e1e6137f323689157b233151 to your computer and use it in GitHub Desktop.
Save akash-ch2812/ffcf6ce7e1e6137f323689157b233151 to your computer and use it in GitHub Desktop.
Crop and image first and then apply OCR
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Users\Akash.Chauhan1\AppData\Local\Tesseract-OCR\tesseract.exe'
# load the original image
image = cv2.imread('Original_Image.jpg')
# get co-ordinates to crop the image
c = line_items_coordinates[1]
# cropping image img = image[y0:y1, x0:x1]
img = image[c[0][1]:c[1][1], c[0][0]:c[1][0]]
plt.figure(figsize=(10,10))
plt.imshow(img)
# convert the image to black and white for better OCR
ret,thresh1 = cv2.threshold(img,120,255,cv2.THRESH_BINARY)
# pytesseract image to string to get results
text = str(pytesseract.image_to_string(thresh1, config='--psm 6'))
print(text)
@JavierTorregrosa92
Copy link

Hi everyone,

This is my very first post in GitHub, so apologies if what I am going to share is not pertinent or does not belong to this place.

I had problems using the script, as it only extracted the very last line of the document, even though there were several lines marked. Therefore, I started browsing, and found a solution proposed in stackoverflow that, at least, worked for me. I don't understand why this worked and the previous one didn't, to be honest, as I am quite new in this field. I hope any of you can find it out, and that this code may help anyone with the same problem.

Of course, credits to Nathancy as the original solver of the problem: https://stackoverflow.com/users/11162165/nathancy
https://stackoverflow.com/questions/58824094/what-causes-pytesseract-to-read-either-the-top-or-bottom-text-line-of-a-dual-lin

import cv2
import pytesseract

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_INV + cv2.THRESH_OTSU)[1]

data = pytesseract.image_to_string(thresh, lang='eng',config='--psm 6')
print(data)

cv2.imshow('thresh', thresh)
cv2.waitKey()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment