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

再运行程序,便正常了。

相关推荐
yc_12241 小时前
用 Visual Studio 远程调试 Linux:从零到流畅的完整指南
linux·ide·visual studio
计算机安禾1 小时前
【Linux从入门到精通】第31篇:防火墙漫谈——iptables与firewalld防护指南
linux·运维·php
下一页盛夏花开2 小时前
ubuntu 20中安装QT以后出现红色空心断点
linux·运维·ubuntu
金色光环2 小时前
FreeModbus释放底层的 TCP 监听端口
服务器·网络·tcp/ip
sanshanjianke2 小时前
Thunderobot 911ME 笔记本 Linux 风扇控制研究
linux
fengyehongWorld5 小时前
TeraTerm ttl脚本登录wsl
linux·teraterm
乌托邦的逃亡者6 小时前
Linux中如何检测IP冲突
linux·运维·tcp/ip
一曦的后花园6 小时前
linux搭建promethes并对接node-exporter指标
linux·运维·服务器
乌托邦的逃亡者6 小时前
CentOS/Openeuler主机中,为一个网卡设置多个IP地址
linux·运维·网络·tcp/ip·centos