如何在java项目中利用ocr实现一个图片文字识别功能

这期内容当中小编将会给大家带来有关如何在java项目中利用ocr实现一个图片文字识别功能,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

创新互联服务项目包括红河网站建设、红河网站制作、红河网页制作以及红河网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,红河网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到红河省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!

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

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

如何在java项目中利用ocr实现一个图片文字识别功能

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

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

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

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

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

如何在java项目中利用ocr实现一个图片文字识别功能

首先是一个临时文件生成用的类以防源文件损坏,参考某位博友的例子@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 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 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 cmd = new ArrayList();  
    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(); 
  }
}  

上述就是小编为大家分享的如何在java项目中利用ocr实现一个图片文字识别功能了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。


本文标题:如何在java项目中利用ocr实现一个图片文字识别功能
网站URL:http://myzitong.com/article/jjodee.html