Java OCR tesseract 图像智能字符识别技术 Java代码实现

article/2025/7/16 9:28:15

接着上一篇OCR所说的,上一篇给大家介绍了tesseract 在命令行的简单用法,当然了要继承到我们的程序中,还是需要代码实现的,下面给大家分享下java实现的例子。


拿代码扫描上面的图片,然后输出结果。主要思想就是利用Java调用系统任务。

下面是核心代码:

package com.zhy.test;import java.io.BufferedReader;import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;import org.jdesktop.swingx.util.OS;public class OCRHelper
{private final String LANG_OPTION = "-l";private final String EOL = System.getProperty("line.separator");/*** 文件位置我防止在,项目同一路径*/private String tessPath = new File("tesseract").getAbsolutePath();/*** @param imageFile*            传入的图像文件* @param imageFormat*            传入的图像格式* @return 识别后的字符串*/public String recognizeText(File imageFile) throws Exception{/*** 设置输出文件的保存的文件目录*/File outputFile = new File(imageFile.getParentFile(), "output");StringBuffer strB = new StringBuffer();List<String> cmd = new ArrayList<String>();if (OS.isWindowsXP()){cmd.add(tessPath + "\\tesseract");} else if (OS.isLinux()){cmd.add("tesseract");} else{cmd.add(tessPath + "\\tesseract");}cmd.add("");cmd.add(outputFile.getName());cmd.add(LANG_OPTION);
//		cmd.add("chi_sim");cmd.add("eng");ProcessBuilder pb = new ProcessBuilder();/***Sets this process builder's working directory.*/pb.directory(imageFile.getParentFile());cmd.set(1, imageFile.getName());pb.command(cmd);pb.redirectErrorStream(true);Process process = pb.start();// tesseract.exe 1.jpg 1 -l chi_sim// Runtime.getRuntime().exec("tesseract.exe 1.jpg 1 -l chi_sim");/*** the exit value of the process. By convention, 0 indicates normal* termination.*/
//		System.out.println(cmd.toString());int w = process.waitFor();if (w == 0)// 0代表正常退出{BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile.getAbsolutePath() + ".txt"),"UTF-8"));String str;while ((str = in.readLine()) != null){strB.append(str).append(EOL);}in.close();} else{String msg;switch (w){case 1:msg = "Errors accessing files. There may be spaces in your image's filename.";break;case 29:msg = "Cannot recognize the image or its selected region.";break;case 31:msg = "Unsupported image format.";break;default:msg = "Errors occurred.";}throw new RuntimeException(msg);}new File(outputFile.getAbsolutePath() + ".txt").delete();return strB.toString().replaceAll("\\s*", "");}
}
代码很简单,中间那部分ProcessBuilder其实就类似Runtime.getRuntime().exec("tesseract.exe 1.jpg 1 -l chi_sim"),大家不习惯的可以使用Runtime。

测试代码:

package com.zhy.test;import java.io.File;public class Test
{public static void main(String[] args){try{File testDataDir = new File("testdata");System.out.println(testDataDir.listFiles().length);int i = 0 ; for(File file :testDataDir.listFiles()){i++ ;String recognizeText = new OCRHelper().recognizeText(file);System.out.print(recognizeText+"\t");if( i % 5  == 0 ){System.out.println();}}} catch (Exception e){e.printStackTrace();}}
}

输出结果:


对比第一张图片,是不是很完美~哈哈 ,当然了如果你只需要实现验证码的读写,那么上面就足够了。下面继续普及图像处理的知识。



-------------------------------------------------------------------我的分割线--------------------------------------------------------------------

当然了,有时候图片被扭曲或者模糊的很厉害,很不容易识别,所以下面我给大家介绍一个去噪的辅助类,绝对碉堡了,先看下效果图。


来张特写:


一个类,不依赖任何jar,把图像中的干扰线消灭了,是不是很给力,然后再拿这样的图片去识别,会不会效果更好呢,嘿嘿,大家自己实验~

代码:

package com.zhy.test;import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;import javax.imageio.ImageIO;public class ClearImageHelper
{public static void main(String[] args) throws IOException{File testDataDir = new File("testdata");final String destDir = testDataDir.getAbsolutePath()+"/tmp";for (File file : testDataDir.listFiles()){cleanImage(file, destDir);}}/*** * @param sfile*            需要去噪的图像* @param destDir*            去噪后的图像保存地址* @throws IOException*/public static void cleanImage(File sfile, String destDir)throws IOException{File destF = new File(destDir);if (!destF.exists()){destF.mkdirs();}BufferedImage bufferedImage = ImageIO.read(sfile);int h = bufferedImage.getHeight();int w = bufferedImage.getWidth();// 灰度化int[][] gray = new int[w][h];for (int x = 0; x < w; x++){for (int y = 0; y < h; y++){int argb = bufferedImage.getRGB(x, y);// 图像加亮(调整亮度识别率非常高)int r = (int) (((argb >> 16) & 0xFF) * 1.1 + 30);int g = (int) (((argb >> 8) & 0xFF) * 1.1 + 30);int b = (int) (((argb >> 0) & 0xFF) * 1.1 + 30);if (r >= 255){r = 255;}if (g >= 255){g = 255;}if (b >= 255){b = 255;}gray[x][y] = (int) Math.pow((Math.pow(r, 2.2) * 0.2973 + Math.pow(g, 2.2)* 0.6274 + Math.pow(b, 2.2) * 0.0753), 1 / 2.2);}}// 二值化int threshold = ostu(gray, w, h);BufferedImage binaryBufferedImage = new BufferedImage(w, h,BufferedImage.TYPE_BYTE_BINARY);for (int x = 0; x < w; x++){for (int y = 0; y < h; y++){if (gray[x][y] > threshold){gray[x][y] |= 0x00FFFF;} else{gray[x][y] &= 0xFF0000;}binaryBufferedImage.setRGB(x, y, gray[x][y]);}}// 矩阵打印for (int y = 0; y < h; y++){for (int x = 0; x < w; x++){if (isBlack(binaryBufferedImage.getRGB(x, y))){System.out.print("*");} else{System.out.print(" ");}}System.out.println();}ImageIO.write(binaryBufferedImage, "jpg", new File(destDir, sfile.getName()));}public static boolean isBlack(int colorInt){Color color = new Color(colorInt);if (color.getRed() + color.getGreen() + color.getBlue() <= 300){return true;}return false;}public static boolean isWhite(int colorInt){Color color = new Color(colorInt);if (color.getRed() + color.getGreen() + color.getBlue() > 300){return true;}return false;}public static int isBlackOrWhite(int colorInt){if (getColorBright(colorInt) < 30 || getColorBright(colorInt) > 730){return 1;}return 0;}public static int getColorBright(int colorInt){Color color = new Color(colorInt);return color.getRed() + color.getGreen() + color.getBlue();}public static int ostu(int[][] gray, int w, int h){int[] histData = new int[w * h];// Calculate histogramfor (int x = 0; x < w; x++){for (int y = 0; y < h; y++){int red = 0xFF & gray[x][y];histData[red]++;}}// Total number of pixelsint total = w * h;float sum = 0;for (int t = 0; t < 256; t++)sum += t * histData[t];float sumB = 0;int wB = 0;int wF = 0;float varMax = 0;int threshold = 0;for (int t = 0; t < 256; t++){wB += histData[t]; // Weight Backgroundif (wB == 0)continue;wF = total - wB; // Weight Foregroundif (wF == 0)break;sumB += (float) (t * histData[t]);float mB = sumB / wB; // Mean Backgroundfloat mF = (sum - sumB) / wF; // Mean Foreground// Calculate Between Class Variancefloat varBetween = (float) wB * (float) wF * (mB - mF) * (mB - mF);// Check if new maximum foundif (varBetween > varMax){varMax = varBetween;threshold = t;}}return threshold;}
}


好了,就到这里。如果这篇文章对你有用,赞一个吧~






http://chatgpt.dhexx.cn/article/mNHgAUVy.shtml

相关文章

六、计算机视觉相关内容

文章目录 前言一、图像增广1.1 常用的图像增广1.1.1 翻转和裁剪1.1.2 变换颜色1.1.3 结合多种图像增广方法 二、微调2.1 微调的步骤2.2 具体案例 三、 目标检测和边界框3.1 边界框 四、锚框五、多尺度目标检测六、目标检测数据集七、单发多框检测(SSD)八、区域卷积神经网络(R-C…

python计算机视觉学习第七章——图像搜索

目录 一、基于内容的图像检索 二、 视觉单词 三、 图像索引 3.1 建立数据库 3.2 添加图像 ​编辑四、在数据库中搜素图像 4.1 利用索引获取候选图像 4.2 用一幅图像进行查询 4.3 确定对比基准并绘制结果 五、 使用几何特性对结果排序 一、基于内容的图像检索 CBI…

使用计算机视觉和深度学习创建现代OCR管道

作者 | 学海无涯yc 编辑 | 3D视觉开发者社区 文章目录 前言1.研究和原型设计2.字深网3.字检测器4.组合式端到端系统5.生产化6.性能调优7.优雅 导读 此篇文章中讲述使用了计算机视觉和深度学习的进步&#xff0c;如双向长短期记忆&#xff08;LSTM&#xff09;&#xff0c;连接…

Java OCR tesseract 图像智能字符识别技术

公司有需求啊&#xff0c;所以就得研究哈&#xff0c;最近公司需要读验证码&#xff0c;于是就研究起了图像识别&#xff0c;应该就是传说中的&#xff08;OCR&#xff1a;光学字符识别OCR&#xff09;&#xff0c;下面把今天的收获整理一个给大家做个分享。 本人程序用的tess…

《深度学习中的字符识别在工业视觉中的实际应用》

最近在公司做了一个构建卷积神经网络来识别字符的项目&#xff0c;编程环境为pycharm2019&#xff0c;使用的是OpenCvPytorch进行项目的实现&#xff0c;因此想总结和归纳一下方法。 本次的字符识别项目可以分为以下几个步骤&#xff1a; 一、图像处理和字符分割 二、创建自…

python计算机视觉-图像检索和识别

目录 一、原理解析 1.1计算机视觉领域的图像分类是什么意思? 1.2图像分类要如何实现? 1.3Bag-of-features算法和过程? 1)提取图像特征 2)训练字典&#xff08; visual vocabulary &#xff09; 3)图片直方图表示 4)训练分类器 1.4TF-IDF? 1.5当前图像分类中会遇到…

使用计算机视觉和深度学习创建现代 OCR 管道

文章目录 研究和原型设计字深网字检测器组合式端到端系统生产化性能调优优雅 在这篇文章中&#xff0c;我们将带您了解我们如何为[【移动文档扫描仪】构建最先进的光学字符识别&#xff08;OCR&#xff09;管道的幕后故事。我们使用了计算机视觉和深度学习的进步&#xff0c;如…

最流行的4个机器学习数据集

最流行的4个机器学习数据集 机器学习算法需要作用于数据&#xff0c;而数据的本质则决定了应用的机器学习算法是否合适&#xff0c;而数据的质量也会决定算法表现的好坏程度。所以会研究数据&#xff0c;会分析数据很重要。本文作为学习研究数据系列博文的开篇&#xff0c;列举…

机器学习——数据集预处理(数据查看和空值处理)

目录 前言 数据集查看 前言 目的&#xff1a;本数据集是为了分析炉丝功率和炉膛温度以及样品盒内部温度之间的关系&#xff0c;分析温场的分布等。 来源&#xff1a;本数据集的来源是实验获得的数据。 特点&#xff1a;特征维度高&#xff0c;数据量大。 数据集查看 1.查…

推荐收藏:50个最佳机器学习公共数据集

外国自媒体mlmemoirs根据github、福布斯、CMU官网等信息&#xff0c;整理了一张50个最佳机器学习公共数据集的榜单&#xff0c;为大家分享一下~ 作者&#xff1a;mlmemoirs 郭一璞 编译 外国自媒体mlmemoirs根据github、福布斯、CMU官网等信息&#xff0c;整理了一张50个最佳…

8种适用于不同机器学习问题的常用数据集

要找到一定特定的数据集可以解决各种机器学习问题&#xff0c;是一件很难的事情。越来越多企业或研究机构将自己的数据集公开&#xff0c;已经成为全球的趋势&#xff0c;这也将有助于大家进行更多研究。 近期&#xff0c;亚马逊高级技术顾问 Will Badr 分享了 8 种适用于不同…

【ML】机器学习数据集:sklearn中回归数据集介绍

目录 1. Boston房价预测数据集2. California房价预测数据集3. 糖尿病预测数据集 在机器学习的教程中&#xff0c;我们会看到很多的demo&#xff0c;这些demo都是基于python中自带的数据集。今天我们将介绍三个用于回归预测的数据集。 1. Boston房价预测数据集 该数据集将在sci…

浅谈机器学习之数据集构建

浅谈机器学习之数据集构建 ​ 正如大家现在知道的&#xff0c;深度学习模型(DL)和机器学习模型(ML)是数据驱动型任务&#xff0c;在近乎完美的数据集面前&#xff0c;模型间的细微差异可以忽略。但要获得覆盖目标场景所有特征的样本&#xff0c;不仅要耗费巨大的人力物力&…

机器学习经典开源数据集盘点

在机器学习任务实施前&#xff0c;如何快速寻找到可用数据集&#xff0c;是令每一位研究人员最头痛的事情。本文为大家列举了八大主流数据集来源&#xff0c;不仅包含大量的数据集信息&#xff0c;而且包含了描述、用法以及一些实施案例等。 01 Kaggle数据集 Kaggle数据集地址h…

免费的机器学习数据集网站(6300+数据集)

今天给大家分享一个免费获取机器学习数据集网站&#xff1a; Machine Learning Datasets | Papers With Code 有想法但没有数据集的同学的福音&#xff0c;网站届满很简洁&#xff0c;及本本上提供的了一般可用的各类数据集&#xff0c;我们可以进行各类影像、评论和点云等数…

学习机器学习算法过程中的常用数据集

文章目录 【数据集1】forge&#xff1a;小型模拟分类问题数据集【数据集2】wave&#xff1a;小型模拟回归问题数据集【数据集3】cancer&#xff1a;中型实际分类问题数据集【数据集4】boston&#xff1a;中型实际回归问题数据集 以下数据集为学习机器学习算法时&#xff0c;经常…

虚拟机系统iso镜像下载_如何下载正版系统镜像

许多网友想装系统&#xff0c;可是不会装(后期会推装系统的文章)&#xff0c;而且网上的系统有的装有全家桶&#xff0c;有的又有捆绑软件&#xff0c;严重的还有病毒。那么&#xff0c;在哪里去下载正版&#xff0c;安全的系统镜像呢 "MSDN&#xff0c;我告诉你"这个…

Win7下安装xp虚拟机

在win7下安装Oracle VM VirtualBox虚拟机&#xff0c;然后在安装xp程序。 准备工作&#xff1a; 1. Oracle VM VirtualBox虚拟机 2. 一张xp安装版的镜像盘&#xff08;这里一定是安装版而不是Ghost版&#xff0c;如果想知道ghost版的会出现什么问题&#xff0c;不妨自己试试。&…

虚拟机系统iso镜像下载_[原版镜像]macOS Mojave 10.14.1 原版 iso 镜像- 虚拟机专用

[原版镜像]macOS Mojave 10.14.1 原版 iso 镜像- 虚拟机专用 Notes: 1. 此镜像仅供用于虚拟机安装, 不能制作启动 u 盘. 2. 此镜像和专栏文章: macOS Mojave 10.14.2 原版镜像 皆可用于虚拟机安装 macOS. 另: 此镜像为苹果官方免费 macOS 镜像和工具制作而成, 没有任何第三方内…

微软官方提供的免费正版 Windows 8.1/Win10/7/XP/Vista 操作系统虚拟机镜像下载

微软官方提供的免费正版 Windows 8.1/Win10/7/XP/Vista 操作系统虚拟机镜像下载 https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/ 相信做过网页开发/前端的同学都知道&#xff0c;测试各个浏览器的兼容性是最麻烦的事情之一&#xff0c;单单 IE 就有 N 个版…