如何使用 PyTesseract 从图像中提取单个字母?

How to extract individual letters from image with PyTesseract?

我正在自学 python 并尝试制作一个简单的程序来识别图像中的字母。这些字母不是句子或段落的形式。我正在尝试使用 cv2 + pytesseract 进行检测,但我似乎无法让它可靠地工作。我开始怀疑我在工作中使用了错误的工具,但我找不到其他任何东西可以帮助我。

这是我的参考图像,其中包含我要提取的字母:

理想情况下,我想要字母以及每个字母(边界框)的坐标。我已经能够对图像应用蒙版和阈值来得到这个:

但我坚持的是 Pytesseract 无法可靠地单独甚至正确地给我字母。这是我的控制台输出...

$ 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