[英]How to extract individual letters from image with PyTesseract?
我正在自學 python 並試圖制作一個簡單的程序來識別圖像中的字母。 這些字母不是句子或段落的形式。 我正在嘗試使用 cv2 + pytesseract 進行檢測,但我似乎無法讓它可靠地工作。 我開始懷疑我使用了錯誤的工具來完成這項工作,但我找不到其他任何東西可以幫助我。
這是我要提取的字母的參考圖像:
理想情況下,我想要字母以及每個字母的坐標(邊界框)。 我已經能夠對圖像應用蒙版和閾值來獲得這個:
但我堅持的是 Pytesseract 無法可靠地單獨甚至正確地給我字母。 這是我的控制台 output...
$ py main.py --image test.png
D
C UL
UO
我正在使用的代碼只是獲取黑白文本圖像並通過 pytesseract 運行它。 我嘗試過使用--psm
標志,但由於文本的形狀很奇怪,我運氣不佳。
text = pytesseract.image_to_string(Image.open(filename), config='-l eng --psm 11')
os.remove(filename)
print(text)
您可以逐個分割和處理每個字母。 您可以查看我的代碼中的詳細信息。
import cv2
import numpy as np
import pytesseract
img = cv2.imread("xO6JI.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
items = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = items[0] if len(items) == 2 else items[1]
img_contour = img.copy()
for i in range(len(contours)):
area = cv2.contourArea(contours[i])
if 100 < area < 10000:
cv2.drawContours(img_contour, contours, i, (0, 0, 255), 2)
detected = ""
for c in contours:
x, y, w, h = cv2.boundingRect(c)
ratio = h/w
area = cv2.contourArea(c)
base = np.ones(thresh.shape, dtype=np.uint8)
if ratio > 0.9 and 100 < area < 10000:
base[y:y+h, x:x+w] = thresh[y:y+h, x:x+w]
segment = cv2.bitwise_not(base)
custom_config = r'-l eng --oem 3 --psm 10 -c tessedit_char_whitelist="ABCDEFGHIJKLMNOPQRSTUVWXYZ" '
c = pytesseract.image_to_string(segment, config=custom_config)
print(c)
detected = detected + c
cv2.imshow("segment", segment)
cv2.waitKey(0)
print("detected: " + detected)
cv2.imshow("img_contour", img_contour)
cv2.waitKey(0)
cv2.destroyAllWindows()
結果
U
O
L
C
D
detected: UOLCD
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.