如何让OpenCV读取嘈杂的图像文本?

时间:2018-07-24 00:33:21

标签: python opencv ocr python-tesseract text-recognition

对于我使用OpenCV和pytesseract在Python中进行的项目,我试图从游戏的健康栏图像中读取一些文本,但是在某些情况下,当我调整参数时,它无法正确读取,完全没有:

import cv2
import numpy as np
import pytesseract
from PIL import Image


def get_string(img_path):
    # Read image with opencv
    img = cv2.imread(img_path)

    # Convert to gray
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Apply dilation and erosion to remove some noise
    kernel = np.ones((1, 1), np.uint8)
    img = cv2.dilate(img, kernel, iterations=1)
    img = cv2.erode(img, kernel, iterations=1)

    # Write image after removed noise
    cv2.imwrite("removed_noise.png", img)

    #  Apply threshold to get image with only black and white
    img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, -15)

    # Write the image after applying opencv...
    cv2.imwrite("thresh.png", img)

    # Recognize text with pytesseract
    result = pytesseract.image_to_string(Image.open("thresh.png"))

    return result


print('--- Starting Text Recognition---')
print(get_string("3.png"))
print("------- Done -------")

我尝试调整cv2.adaptiveThreshold()的参数,这似乎使图像更清晰,但仍然没有结果。我已经附加了游戏中出现的源图像,并在保存图像的代码中添加了两个阶段的结果图像。我计划在程序执行时多次使用此方法。 我是Python,OpenCV和OCR的新手。请帮助我使我的程序能够阅读此文本。如果还有其他方法,我不会介意建议。

要读取的图像:

-Image to Read-

已删除的噪声图像:

*Removed Noise Image*

阈值图像:

=Threshold Image=

0 个答案:

没有答案