Mac 上使用 Tesseract OCR 识别图片文本

Tesseract OCR 引擎:Tesseract是一个开源的OCR引擎,你需要先安装它。可以从Tesseract官方网站(https://github.com/tesseract-ocr/tesseract)下载适用于你的操作系统的安装程序或源代码,并按照官方文档进行安装。

Tesseract OCR 对于低分辨率或模糊的图片可能无法准确识别。尝试使用更高分辨率和清晰度的图片来提高识别结果的准确性。对于 Mac 上的截图,一般都是很清晰的,所以这个缺点影响不大。

在 Mac 上,使用官网推荐的方式安装:

shell 复制代码
brew install tesseract

The tesseract directory can then be found using brew info tesseract, e.g.

bash 复制代码
/usr/local/Cellar/tesseract/5.3.2/bin/tesseract

demo:

python 复制代码
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])
相关推荐
goodmao8 小时前
【macOS】【mouse】设置鼠标大小
macos·计算机外设·鼠标·mouse
五点钟科技8 小时前
Deepseek-OCR:《DeepSeek-OCR: Contexts Optical Compression》 论文要点解读
人工智能·llm·ocr·论文·大语言模型·deepseek·deepseek-ocr
Magnum Lehar8 小时前
macos信息采集器appledataharvester-3
macos·网络安全·系统安全
川川菜鸟10 小时前
Claude Code 安装与配置完整指南(Mac)
macos
WarmSword11 小时前
mac上用cursor/vscode调试root权限进程
c++·ide·vscode·macos·mac
Magnum Lehar12 小时前
macos的信息采集器appledataHarvester-2
macos·网络安全·系统安全
echo-niuben13 小时前
macOS 端已如何正常安装并配置XcodeBuildMCP ?
macos
刘某某.14 小时前
Mac上缺失宋体字体,只有宋体-简
macos
Tom·Ge15 小时前
在macOS上安装OpenClaw并实现Chrome网站自动化测试
chrome·macos·策略模式
Lo-Y-eH15 小时前
Mac 安装 Ollama 部署 DeepSeek 模型
macos·ollama·deepseek·cherry studio