centos7部署tesseract实现java+tess4j进行图片识别

部署tesseract

部分安装包和语言包已打包放在【免费】leptonica及tesserac压缩包以及tessdata各语言集合包资源-CSDN文库

可自行下载,如文章有错漏望大佬们指点指点,本人小白尝试分享

安装依赖包

  1. 安装依赖包:

yum -y install automake libtool libtiff-devel libjpeg-devel libpng-devel
  1. 还有个pkg-config包yum源里没有,需要下载后在安装

下载pkg-config:

wget https://pkg-config.freedesktop.org/releases/pkg-config-0.29.tar.gz
  1. 解压:

tar -xvf pkg-config-0.29.tar.gz

4. 进入解压后的文件夹

./configure --with-internal-glib
  1. 编译:

make
make check
make install

注意:不安装pkg-config,等下./configure Tesseract时会出现以下错误

configure: error: Leptonica 1.74 or higher is required. Try to install libleptonica-dev package.

编译安装Leptonica

  1. 官方source下载页面可找到最新的Leptonica

在这以leptonica-1.78.0为例,先到官网下载所需版本,这里下载1.78.0

  1. 解压编译

tar -zxvf leptonica-1.78.0.tar.gz
cd leptonica-1.78.0/
./configure
make && make install
  1. 将leptonica加入系统变量中

    vim /etc/profile
    #文末加入
    export LD_LIBRARY_PATH=$LD_LIBRARY_PAYT:/usr/local/lib
    export LIBLEPT_HEADERSDIR=/usr/local/include
    export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
    #保存退出后运行:
    source /etc/profile

编译安装Tesseract

  1. 以下以4.1.0为例

下载链接:

#或者
wget https://codeload.github.com/tesseract-ocr/tesseract/tar.gz/4.1.0
  1. 解压编译:

tar -xvf 4.1.0
cd tesseract-4.1.0/
./autogen.sh
./configure --with-extra-includes=/usr/local/include --with-extra-libraries=/usr/local/lib
make && make install
  1. 验证:

    tesseract -v
  2. 测试

tesseract -v

如上图表示安装成功

下载语言包并配置环境

  1. 下载Tesseract语言包

地址:

  1. 将语言包放在指定位置,这里以放在项目同路径为例

cp tessdata /usr/local/myapp/travel-system -R
  1. 配置语言包环境变量:

vim ~/.bash_profile
#加入一下内容
export TESSDATA_PREFIX=/usr/local/tess4j/tessdata
#保存并退出

刷新配置:

source ~/.bash_profile

4.测试:

tesseract 图片地址 out -l eng+chi_sim
#查看解析结果
cat 图片地址

java实现图片识别接口

本例为springboot2.7.6

  1. 在pom.xml中引入依赖

    <!-- 图片识别Tesseract OCR -->
    <dependency>
        <groupId>net.sourceforge.tess4j</groupId>
        <artifactId>tess4j</artifactId>
        <version>4.5.4</version>
    </dependency>
  2. 下载语言包

    可放在任意路径

  3. 创建OcrService类:

@Service
public class OcrService {

    @Resource
    private Tesseract tesseract;

    public String recognizeText(File imageFile) throws TesseractException {
        return tesseract.doOCR(imageFile);
    }

    public String recognizeTextFromUrl(String imageUrl) throws Exception {
        URL url = new URL(imageUrl);
        InputStream in = url.openStream();
        // 临时文件名
        String tempFileName = "downloaded." + getImageFormat(imageUrl);
        Files.copy(in, Paths.get(tempFileName), StandardCopyOption.REPLACE_EXISTING);

        File imageFile = new File(tempFileName);
        return recognizeText(imageFile);
    }

    // 获取图片格式
    private String getImageFormat(String imageUrl) {
        String format = "";
        try {
            URLConnection connection = new URL(imageUrl).openConnection();
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            String contentType = connection.getHeaderField("Content-Type");
            if (contentType.equals("image/jpeg")) {
                format = "jpg";
            } else if (contentType.equals("image/png")) {
                format = "png";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return format;
    }
}
  1. 创建REST控制器:

@RestController
@RequestMapping("/ocr")
public class OcrController {

    @Resource
    private OcrService ocrService;

    @PostMapping("/upload")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            //打开系统临时文件存储处并将下载下来的图片放入该位置
            File convFile = new File(System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename());
            file.transferTo(convFile);
            // 获取识别结果
            String result = ocrService.recognizeText(convFile);
            System.out.println(result);
            return Result.success(result,"读取成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("识别发生错误:" + e.getMessage());
        }
    }

    @GetMapping("/recognize-url")
    public ResponseEntity<String> recognizeFromUrl(@RequestParam("imageUrl") String imageUrl) {
        try {
            String result = ocrService.recognizeTextFromUrl(imageUrl);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("从URL识别发生错误:" + e.getMessage());
        }
    }
}
  1. 配置类

@Configuration
public class TesseractOcrConfiguration {

   @Value("${tess4j.datapath}")
   private String dataPath;

   @Bean
   public Tesseract tesseract() {

      Tesseract tesseract = new Tesseract();
      // 设置训练数据文件夹路径
      tesseract.setDatapath(dataPath);
      //设置分辨率
      tesseract.setTessVariable("user_defined_dpi", "300");
      // 设置为中文简体
      tesseract.setLanguage("chi_sim");
      return tesseract;
   }
}
  1. 在yml中写入路径,方便维护:

# 训练数据文件夹的路径,语言包路径,部署到服务器注意修改为服务器上语言包路径
tess4j:
#  datapath: F:\JAVA\travel-system\tessdataLanguagePackage
  datapath: /usr/local/myapp/travel-system/tessdataLanguagePackage
  1. 启动测试

本例为本地启动测试,使用apifox

如下:

  • 43
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值