Tesseract OCR を使用して Mac で画像テキストを認識する

Tesseract OCR エンジン: Tesseract はオープンソースの OCR エンジンであるため、最初にインストールする必要があります。Tesseract 公式 Web サイト (https://github.com/tesseract-ocr/tesseract) からオペレーティング システムのインストーラーまたはソース コードをダウンロードし、公式ドキュメントに従ってインストールできます。

Tesseract OCR は、低解像度の画像やぼやけた画像に対しては正確ではない可能性があります。認識結果の精度を向上させるには、より高解像度で鮮明な画像を使用してみてください。Mac のスクリーンショットの場合、通常は非常に鮮明であるため、この欠点はほとんど影響しません。

Mac の場合は、公式 Web サイトで推奨されている方法を使用してインストールします。

brew install tesseract

tesseract ディレクトリは、brew info tesseract を使用して見つけることができます。

/usr/local/Cellar/tesseract/5.3.2/bin/tesseract

デモ:

import pytesseract
from PIL import Image

# 可以写一个函数 crop_picture 将原图裁剪一下,只保留想要识别文本的部分,这样识别更加准确一些。
def crop_picture(picture_path, crop_box: list):
    """
    crap picture with crop_box
    :param picture_path: picture to be crapped
    :param crop_box: crop region, eg: [100, 200, 300, 350]
    :return: path of crapped picture
    """
    dirname = os.path.dirname(picture_path)
    basename = os.path.basename(picture_path)
    new_basename = ''.join([basename.split('.')[0], '_new.', basename.split('.')[1]])

    picture_origin = Image.open(picture_path)
    picture_origin_size = picture_origin.size
    if crop_box[2] is None:
        crop_box[2] = picture_origin_size[0]
    if crop_box[3] is None:
        crop_box[3] = picture_origin_size[1]
    picture_new = picture_origin.crop(tuple(crop_box))

    picture_new_path = os.path.join(dirname, new_basename)
    picture_new.save(picture_new_path)
    return picture_new_path

def get_text_from_picture(picture_path, crop_box: list):
    """
    get text from picture
    :param picture_path: picture to be crapped
    :param crop_box: crop region, eg: [100, 200, 300, 350]
    :return: text
    """
    pytesseract.pytesseract.tesseract_cmd = r'/usr/local/Cellar/tesseract/5.3.2/bin/tesseract'
    picture_new_path = crop_picture(picture_path, crop_box=crop_box)
    image = Image.open(picture_new_path)
    text = pytesseract.image_to_string(image, lang='eng')
    print(text)
    return text

if __name__ == '__main__':
    get_text_from_picture('my_picture_path', crop_box=[585, 360, None, 800])

Supongo que te gusta

Origin blog.csdn.net/qq_31362767/article/details/131943091
Recomendado
Clasificación