全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

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

接着上一篇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 histogram 
  for (int x = 0; x < w; x++) 
  { 
   for (int y = 0; y < h; y++) 
   { 
    int red = 0xFF & gray[x][y]; 
    histData[red]++; 
   } 
  } 
 
  // Total number of pixels 
  int 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 Background 
   if (wB == 0) 
    continue; 
 
   wF = total - wB; // Weight Foreground 
   if (wF == 0) 
    break; 
 
   sumB += (float) (t * histData[t]); 
 
   float mB = sumB / wB; // Mean Background 
   float mF = (sum - sumB) / wF; // Mean Foreground 
 
   // Calculate Between Class Variance 
   float varBetween = (float) wB * (float) wF * (mB - mF) * (mB - mF); 
 
   // Check if new maximum found 
   if (varBetween > varMax) 
   { 
    varMax = varBetween; 
    threshold = t; 
   } 
  } 
 
  return threshold; 
 } 
} 

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


# Java  # 图像字符识别  # Java图像文字识别  # OCR  # tesseract  # Java使用Tesseract-Ocr识别数字  # Java使用Tesseract-OCR实战教程  # 不是很  # 给大家  # 加亮  # 上一篇  # 当然了  # 会不会  # 很简单  # 我给  # 然后再  # 可以使用  # 验证码  # 第一张  # 很厉害  # 不习惯  # 很不  # 图像处理  # 先看  # 命令行  # 大家多多  # 你只需要 


相关文章: 图册素材网站设计制作软件,图册的导出方式有几种?  网站制作的方法有哪些,如何将自己制作的网站发布到网上?  西安大型网站制作公司,西安招聘网站最好的是哪个?  C#如何序列化对象为XML XmlSerializer用法  如何生成腾讯云建站专用兑换码?  建站之星如何助力网站排名飙升?揭秘高效技巧  如何在景安服务器上快速搭建个人网站?  商务网站制作工程师,从哪几个方面把握电子商务网站主页和页面的特色设计?  如何将凡科建站内容保存为本地文件?  如何用wdcp快速搭建高效网站?  金*站制作公司有哪些,金华教育集团官网?  制作网站怎么制作,*游戏网站怎么搭建?  h5网站制作工具有哪些,h5页面制作工具有哪些?  如何在IIS管理器中快速创建并配置网站?  建站168自助建站系统:快速模板定制与SEO优化指南  怎么制作网站设计模板图片,有电商商品详情页面的免费模板素材网站推荐吗?  我的世界制作壁纸网站下载,手机怎么换我的世界壁纸?  官网网站制作腾讯审核要多久,联想路由器newifi官网  c# 在ASP.NET Core中管理和取消后台任务  如何做网站制作流程,*游戏网站怎么搭建?  网站按钮制作软件,如何实现网页中按钮的自动点击?  英语简历制作免费网站推荐,如何将简历翻译成英文?  如何选择CMS系统实现快速建站与SEO优化?  新网站制作渠道有哪些,跪求一个无线渠道比较强的小说网站,我要发表小说?  如何通过WDCP绑定主域名及创建子域名站点?  建设网站制作价格,怎样建立自己的公司网站?  装修招标网站设计制作流程,装修招标流程?  合肥做个网站多少钱,合肥本地有没有比较靠谱的交友平台?  小自动建站系统:AI智能生成+拖拽模板,多端适配一键搭建  怎么将XML数据可视化 D3.js加载XML  香港服务器选型指南:免备案配置与高效建站方案解析  威客平台建站流程解析:高效搭建教程与设计优化方案  淘宝制作网站有哪些,淘宝网官网主页?  北京网站制作的公司有哪些,北京白云观官方网站?  一键制作网站软件下载安装,一键自动采集网页文档制作步骤?  官网自助建站平台指南:在线制作、快速建站与模板选择全解析  公司网站制作需要多少钱,找人做公司网站需要多少钱?  个人网站制作流程图片大全,个人网站如何注销?  SQL查询语句优化的实用方法总结  如何通过二级域名建站提升品牌影响力?  内网网站制作软件,内网的网站如何发布到外网?  如何处理“XML格式不正确”错误 常见XML well-formed问题解决方法  官网建站费用明细查询_企业建站套餐价格及收费标准指南  建站主机数据库如何配置才能提升网站性能?  如何在云主机上快速搭建多站点网站?  网页制作模板网站推荐,网页设计海报之类的素材哪里好?  已有域名如何快速搭建专属网站?  如何在西部数码注册域名并快速搭建网站?  如何选择最佳自助建站系统?快速指南解析优劣  大学网站设计制作软件有哪些,如何将网站制作成自己app? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。