python detect text from image code example
Example 1: image processing for OCR using python
1|
2| import cv2
3| import pytesseract
5|
6| image = cv2.imread(sample_image.png’)
7|
8| gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
9|
10|
11|
11|threshold_img = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
12|
13| cv2.imshow(‘threshold image’, threshold_img)
14|
15| cv2.waitKey(0)
16|
17| cv2.destroyAllWindows()
Example 2: text detection from image using opencv python
import cv2
import numpy as np
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
image = cv2.imread('1.jpg')
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower = np.array([0, 0, 218])
upper = np.array([157, 54, 255])
mask = cv2.inRange(hsv, lower, upper)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,3))
dilate = cv2.dilate(mask, kernel, iterations=5)
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)
ar = w / float(h)
if ar < 5:
cv2.drawContours(dilate, [c], -1, (0,0,0), -1)
result = 255 - cv2.bitwise_and(dilate, mask)
data = pytesseract.image_to_string(result, lang='eng',config='--psm 6')
print(data)
cv2.imshow('mask', mask)
cv2.imshow('dilate', dilate)
cv2.imshow('result', result)
cv2.waitKey()