最近在开发的时候需要识别图片中的一些文字,网上找了相关资料之后,发现google有一个离线的工具,以下为java使用的demo

在此之前,使用这个工具需要在本地安装OCR工具:

下面一个是一定要安装的离线包,建议默认安装

上面一个是中文的语言包,如果网络可以翻墙的童鞋可以在安装的时候就选择语言包在线安装,有多种语言可供选择,默认只有英文的

exe安装好之后,把上面一个文件拷到安装目录下tessdata文件夹下

如C:\Program Files (x86)\Tesseract-OCR\tessdata下

然后下面两个是可选包,如果图片不做临时文件处理的话,可以不需要带的

首先是一个临时文件生成用的类以防源文件损坏,参考某位博友的例子@Gunner

package org.ink.image.textrz;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Locale; import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream; import com.sun.media.imageio.plugins.tiff.TIFFImageWriteParam; public class ImageIOHelper {
private Locale locale=Locale.CHINESE;
/**
* user set locale Construct
* @param locale
*/
public ImageIOHelper(Locale locale){
this.locale=locale;
} /**
* default construct using default locale Locale.CHINESE
*/
public ImageIOHelper(){ }
/**
* create tempFile of Image in order to prevent damaging original file
* @param imageFile
* @param imageFormat like png,jps .etc
* @return TempFile of Image
* @throws IOException
*/
public File createImage(File imageFile, String imageFormat) throws IOException {
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
ImageReader reader = readers.next();
ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
reader.setInput(iis);
IIOMetadata streamMetadata = reader.getStreamMetadata();
TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.CHINESE);
tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("tiff");
ImageWriter writer = writers.next();
BufferedImage bi = reader.read(0);
IIOImage image = new IIOImage(bi,null,reader.getImageMetadata(0));
File tempFile = tempImageFile(imageFile);
ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile);
writer.setOutput(ios);
writer.write(streamMetadata, image, tiffWriteParam);
ios.close();
iis.close();
writer.dispose();
reader.dispose();
return tempFile;
}
/**
* add suffix to tempfile
* @param imageFile
* @return
* @throws IOException
*/
private File tempImageFile(File imageFile) throws IOException {
String path = imageFile.getPath();
StringBuffer strB = new StringBuffer(path);
strB.insert(path.lastIndexOf('.'),"_text_recognize_temp");
String s=strB.toString().replaceFirst("(?<=//.)(//w+)$", "tif");
Runtime.getRuntime().exec("attrib "+"\""+s+"\""+" +H"); //设置文件隐藏
return new File(strB.toString());
} }

下面是真正识别的内容:

package org.ink.image.textrz;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale; import org.jdesktop.swingx.util.OS; /**
* TEXT Recognize Utils
* @author ink.Flower
*
*/
public class OCRUtil {
private final String LANG_OPTION = "-l"; //英文字母小写l,并非数字1
private final String EOL = System.getProperty("line.separator");
private String tessPath = "C://Program Files (x86)//Tesseract-OCR";//ocr默认安装路径
private String transname="chi_sim";//默认中文语言包,识别中文 /**
* Construct method of OCR ,set Tesseract-OCR install path
* @param tessPath Tesseract-OCR install path
* @param transFileName traningFile name like eng.traineddata
*/
public OCRUtil(String tessPath,String transFileName){
this.tessPath=tessPath;
this.transname=transFileName;
}
/**
* Construct method of OCR,default path is "C://Program Files (x86)//Tesseract-OCR"
*/
public OCRUtil(){ } public String getTessPath() {
return tessPath;
}
public void setTessPath(String tessPath) {
this.tessPath = tessPath;
}
public String getTransname() {
return transname;
}
public void setTransname(String transname) {
this.transname = transname;
}
public String getLANG_OPTION() {
return LANG_OPTION;
}
public String getEOL() {
return EOL;
} /**
* recognize text in image
* @param imageFile
* @param imageFormat
* @return text recognized in image
* @throws Exception
*/
public String recognizeText(File imageFile,String imageFormat)throws Exception{
File tempImage = new ImageIOHelper().createImage(imageFile,imageFormat);
return ocrImages(tempImage, imageFile);
} /**
* recognize text in image
* @param imageFile
* @param imageFormat
* @param locale
* @return text recognized in image
* @throws Exception
*/
public String recognizeText(File imageFile,String imageFormat,Locale locale)throws Exception{
File tempImage = new ImageIOHelper(locale).createImage(imageFile,imageFormat);
return ocrImages(tempImage, imageFile); }
/**
*
* @param tempImage
* @param imageFile
* @return
* @throws IOException
* @throws InterruptedException
*/
private String ocrImages(File tempImage,File imageFile) throws IOException, InterruptedException{
File outputFile = new File(imageFile.getParentFile(),"output");
Runtime.getRuntime().exec("attrib "+"\""+outputFile.getAbsolutePath()+"\""+" +H"); //设置文件隐藏
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(transname);
ProcessBuilder pb = new ProcessBuilder();
pb.directory(imageFile.getParentFile());
cmd.set(1, tempImage.getName());
pb.command(cmd);
pb.redirectErrorStream(true);
Process process = pb.start();
int w = process.waitFor();
tempImage.delete();//删除临时正在工作文件
if(w==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 recongnize the image or its selected region.";
break;
case 31:
msg = "Unsupported image format.";
break;
default:
msg = "Errors occurred.";
}
tempImage.delete();
throw new RuntimeException(msg);
}
new File(outputFile.getAbsolutePath()+".txt").delete();
return strB.toString();
}
}

在实验中发现,如果对有多个文字的大图进行直接识别的话,效果可能比较差,所以可以参考另一篇切图的博文,将图片取一块之后再识别

http://www.cnblogs.com/inkflower/p/6642089.html    ←我是链接

这样成功率会提高很多。

以上为离线识别版本,效率因图而已,具体使用的时候可以总结分析

另外,博主也在网上看到百度也有图片文字识别的工具

百度OCR企业版

以上这个貌似是付费的,如果要免费的可以网上找找,另外API也可以找找

java 图片文字识别 ocr的更多相关文章

  1. 【图片识别】java 图片文字识别 ocr (转)

    http://www.cnblogs.com/inkflower/p/6642264.html 最近在开发的时候需要识别图片中的一些文字,网上找了相关资料之后,发现google有一个离线的工具,以下为 ...

  2. 如何大批量的识别图片上的文字,批量图片文字识别OCR软件系统

    软件不需要安装,直接双击打开就可以用,废话不多说直接上图好了,方便说明问题 批量图片OCR(批量名片识别.批量照片识别等)识别,然后就下来研究了一下,下面是成果 使用步骤:打开单个图片识别,导入文件夹 ...

  3. python实现中文图片文字识别--OCR about chinese text--tesseract

    0.我的环境: win7 32bits python 3.5 pycharm 5.0 1.相关库 安装pillow: pip install pillow 安装tesseract: tesseract ...

  4. 小试Office OneNote 2010的图片文字识别功能(OCR)

    原文:小试Office OneNote 2010的图片文字识别功能(OCR) 自Office 2003以来,OneNote就成为了我电脑中必不可少的软件,它集各种创新功能于一身,可方便的记录下各种类型 ...

  5. 一篇文章搞定百度OCR图片文字识别API

    一篇文章搞定百度OCR图片文字识别API https://www.jianshu.com/p/7905d3b12104

  6. 【原】Coursera—Andrew Ng机器学习—课程笔记 Lecture 18—Photo OCR 应用实例:图片文字识别

    Lecture 18—Photo OCR 应用实例:图片文字识别 18.1 问题描述和流程图 Problem Description and Pipeline 图像文字识别需要如下步骤: 1.文字侦测 ...

  7. JAVA的图片文字识别技术

    从2013年的记录看,JAVA中图片文字识别技术大部分采用ORC的tesseract的软件功能,后来渐渐开放了java-api调用接口. 图片文字识别技术,还是采用训练的方法.并未从根本上解决图片与文 ...

  8. [C13] 应用实例:图片文字识别(Application Example: Photo OCR)

    应用实例:图片文字识别(Application Example: Photo OCR) 问题描述和流程图(Problem Description and Pipeline) 图像文字识别应用所作的事是 ...

  9. python3 图片文字识别

    最近用到了图片文字识别这个功能,从网上搜查了一下,决定利用百度的文字识别接口.通过测试发现文字识别率还可以.下面就测试过程简要说明一下 1.注册用户 链接:https://login.bce.baid ...

随机推荐

  1. initerrlog: 无法打开错误日志文件 'D:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Log 解决办法

    initerrlog: 无法打开错误日志文件 'D:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Log 1. 设置 ...

  2. AC日记——[HNOI2014]世界树 bzoj 3572

    3572 思路: 虚树+乱搞: 代码: #include <bits/stdc++.h> using namespace std; #define maxn 300005 #define ...

  3. Oracle 数据库分页查询的三种方法

    一.Oracle 数据库分页查询的三种方法 1.简介 不能对 rownum 使用 >(大于或等于 1 的数值).>=(大于 1 的数值).=(不等于 1 的数值),否则无结果.所以直接用 ...

  4. 深入解析php中的foreach问题

    本篇文章是对php中的foreach问题进行了详细的分析介绍,需要的朋友参考下   前言:php4中引入了foreach结构,这是一种遍历数组的简单方式.相比传统的for循环,foreach能够更加便 ...

  5. Python开发基础-Day4-布尔运算、集合

    布尔值 True 真 False 假 所有的数据类型都自带布尔值,数据只有在0,None和空的时候为False. print(bool()) print(bool()) print(bool('')) ...

  6. 【hdu1280】前M大的数

    前m大的数 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submi ...

  7. 【后缀自动机】poj1509 Glass Beads

    字符串最小表示 后缀自动机 O(n) 把串复制一次,链接在后面之后,建立SAM,贪心地在SAM上转移,每次贪心地选择最小的字符,转移的长度为n时停止. 输出时由于要最靠前的,所以要在endpos集合中 ...

  8. 【FFT】BZOJ2179- FFT快速傅立叶

    [题目大意] 给出n位十进制a和b,求a*b. [思路] FFT.感觉弄起来比较麻烦,不如直接背板子. 注意一下MAXN的取值,我一开始非常随意地就写了60000*2+50,其实n是要扩展到最接近的2 ...

  9. 推荐系统中的SVD

    本文主要参考:Factorization Meets the Neighborhood: a Multifaceted Collaborative Filtering Model 在用户对自己需求相对 ...

  10. JAVA EE 中之AJAX 无刷新地区下拉列表三级联动

    JSP页面 <html> <head> <meta http-equiv="Content-Type" content="text/html ...