Windows下Java调用OCR进行图片识别

时间:2022-08-30 16:28:53

使用java语言,通过tesseract-ocr对图片进行识别。

1.tesseract-ocr

下载windows版本并安装。

2.程序如下:

a.imageiohelper类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package ocr;
 
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 {
 /**
 * 图片文件转换为tif格式
 * @param imagefile 文件路径
 * @param imageformat 文件扩展名
 * @return
 */
 public static file createimage(file imagefile, string imageformat) {
 file tempfile = null;
 try {
  iterator<imagereader> readers = imageio.getimagereadersbyformatname(imageformat);
  imagereader reader = readers.next();
 
  imageinputstream iis = imageio.createimageinputstream(imagefile);
  reader.setinput(iis);
  //read the stream metadata
  iiometadata streammetadata = reader.getstreammetadata();
  
  //set up the writeparam
  tiffimagewriteparam tiffwriteparam = new tiffimagewriteparam(locale.chinese);
  tiffwriteparam.setcompressionmode(imagewriteparam.mode_disabled);
  
  //get tif writer and set output to file
  iterator<imagewriter> writers = imageio.getimagewritersbyformatname("tiff");
  imagewriter writer = writers.next();
  
  bufferedimage bi = reader.read(0);
  iioimage image = new iioimage(bi,null,reader.getimagemetadata(0));
  tempfile = tempimagefile(imagefile);
  imageoutputstream ios = imageio.createimageoutputstream(tempfile);
  writer.setoutput(ios);
  writer.write(streammetadata, image, tiffwriteparam);
  ios.close();
  
  writer.dispose();
  reader.dispose();
  
 } catch (ioexception e) {
  e.printstacktrace();
 }
 return tempfile;
 }
 
 private static file tempimagefile(file imagefile) {
 string path = imagefile.getpath();
 stringbuffer strb = new stringbuffer(path);
 strb.insert(path.lastindexof('.'),0);
 return new file(strb.tostring().replacefirst("(?<=//.)(//w+)$", "tif"));
 }
 
}

b.ocr核心类

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package ocr;
 
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 ocr {
 private final string lang_option = "-l"; //英文字母小写l,并非数字1
 private final string eol = system.getproperty("line.separator");
 private string tesspath = "c://program files//tesseract-ocr";
 //private string tesspath = new file("tesseract").getabsolutepath();
 
 public string recognizetext(file imagefile,string imageformat)throws exception{
 file tempimage = imageiohelper.createimage(imagefile,imageformat);
 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();
 pb.directory(imagefile.getparentfile());
 
 cmd.set(1, tempimage.getname());
 pb.command(cmd);
 pb.redirecterrorstream(true);
 
 process process = pb.start();
 //tesseract.exe 1.jpg 1 -l chi_sim
 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();
 }
}

c.main

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package ocr;
import java.io.file;
import java.io.ioexception;
 
public class testocr {
 
 /**
 * @param args
 */
 public static void main(string[] args) {
 //输入图片地址
 string path = "d://test//test.bmp"
    try
      string valcode = new ocr().recognizetext(new file(path), "bmp"); 
      system.out.println(valcode); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } catch (exception e) {
  e.printstacktrace();
 
 }
 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/gaokao2011/article/details/23421477