Linux中安装tesserocr遇到的那些坑

一、遇到的问题:

linux命令安装,提示失败

复制代码
pip install tesserocr

二、安装步骤:

先安装Tesseract OCR

  1. 更新软件源

    复制代码
    sudo apt-get update
  2. 安装Tesseract OCR

    复制代码
    sudo apt-get install tesseract-ocr
  3. 安装语言包(如果需要识别特定语言的文本,需要安装相应的语言包):

    复制代码
    sudo apt-get install tesseract-ocr-[language]

    其中 [language] 是你需要安装的语言代码,例如英语是 eng,中文是 chi_sim

  4. 验证安装是否成功

    复制代码
    tesseract --version

    如果一切正常,你将看到Tesseract的版本信息。

  5. 使用Tesseract : 例如,要将 image.jpg 的文本识别并保存到 output.txt 文件中,可以执行以下命令:

    复制代码
    tesseract image.jpg output.txt

再安装tesserocr

复制代码
pip install tesserocr

四、运行程序:

复制代码
    import tesserocr
	from PIL import Image
	
	
	def preprocess_image(image_path):
	    image = Image.open(image_path)
	    # 转换为灰度图像
	    image = image.convert('L')
	    # 二值化处理
	    threshold = 127
	    table = []
	    for i in range(256):
	        if i < threshold:
	            table.append(0)
	        else:
	            table.append(1)
	    image = image.point(table, '1')
	    return image
	
	
	def recognize_captcha(image):
	    text = tesserocr.image_to_text(image)
	
	    return text
	
	
	if __name__ == '__main__':
	    imgs = ["/root/zhzhx/1.jpg"]
	    for i in range(len(imgs)):
	        # 预处理验证码图片
	        preprocessed_image = preprocess_image(imgs[i])
	        # 识别验证码
	        captcha_text = recognize_captcha(preprocessed_image)
	        print(captcha_text)

报错:

复制代码
File "tesserocr.pyx", line 2401, in tesserocr._tesserocr.image_to_text

分析原因:TESSDATA_PREFIX环境变量未设置

五、TESSDATA_PREFIX环境变量设置步骤:

TESSDATA_PREFIX环境变量添加到系统环境变量中,设置其值为/usr/share/tesseract-ocr/4.00/tessdata,按照以下步骤操作:

  1. 编辑环境变量配置文件 : 打开终端,并根据你的Linux发行版,选择编辑/etc/environment/etc/profile,或者为当前用户编辑~/.bashrc~/.profile文件。这里以~/.bashrc为例:

    复制代码
    nano ~/.bashrc
  2. 添加TESSDATA_PREFIX变量 : 在打开的.bashrc文件末尾添加以下行:

    复制代码
    export TESSDATA_PREFIX="/usr/share/tesseract-ocr/4.00/tessdata"

    确保路径/usr/share/tesseract-ocr/4.00/tessdata是正确的,并且是你的Tesseract OCR语言数据文件所在的目录。

  3. 保存并关闭文件 : 如果你使用的是nano编辑器,可以按Ctrl + X退出,然后按Y确认保存更改,最后按Enter键保存文件。

  4. 重新加载环境变量 : 为了让更改立即生效,你需要重新加载.bashrc文件:

    复制代码
    source ~/.bashrc
  5. 验证环境变量是否设置正确 : 你可以通过在终端运行以下命令来检查TESSDATA_PREFIX环境变量是否设置正确:

    复制代码
    echo $TESSDATA_PREFIX

    这应该会输出你设置的路径:/usr/share/tesseract-ocr/4.00/tessdata

再运行程序,便正常了。

相关推荐
Kaede62 小时前
如何应对Linux云服务器磁盘空间不足的情况
linux·运维·服务器
Zfox_4 小时前
Redis:Hash数据类型
服务器·数据库·redis·缓存·微服务·哈希算法
apocelipes7 小时前
Linux c 运行时获取动态库所在路径
linux·c语言·linux编程
ABB自动化8 小时前
for AC500 PLCs 3ADR025003M9903的安全说明
服务器·安全·机器人
努力学习的小廉8 小时前
深入了解linux系统—— 进程池
linux·运维·服务器
秃头菜狗9 小时前
各个主要目录的功能 / Linux 常见指令
linux·运维·服务器
利刃大大9 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目
2301_793102499 小时前
Linux——MySql数据库
linux·数据库
vfvfb9 小时前
bat批量去掉本文件夹中的文件扩展名
服务器·windows·批处理·删除扩展名·bat技巧
jiunian_cn10 小时前
【Linux】centos软件安装
linux·运维·centos