验证码图片识别

最近弄了一个验证码图片识别的功能,效果还不错……
/**
 * 图片处理类
 *
 */
public class ImageUtil {
 private static String imagePath;//待识别图像路径
 public ImageUtil(String inputImagePath) {
  imagePath = inputImagePath; 
 }
 
 /**
  * 读取验证码中的数字
  * @return
  */
 public synchronized String readImages(){
  String returnStr = "";
  BufferedImage bufferedImage = null;
  try {
   if(imagePath.contains("file:")){
    imagePath.replaceAll("file:", "");
   }
   bufferedImage = ImageIO.read(new File(imagePath));
   BufferedImage newim[] = new BufferedImage[4];
   
   //将图像分成四块,因为要处理的文件有四个数字。
   newim[0] = bufferedImage.getSubimage(5,3,11,bufferedImage.getHeight()-5);
   newim[1] = bufferedImage.getSubimage(18,3,11,bufferedImage.getHeight()-5);
   newim[2] = bufferedImage.getSubimage(31,3,11,bufferedImage.getHeight()-5);
   newim[3] = bufferedImage.getSubimage(44,3,11,bufferedImage.getHeight()-5);
   
   for (int i = 0; i < newim.length; i++) {
    ImageFilter filter = new ImageFilter(newim[i]);
    BufferedImage tempImage = filter.changeGrey();
    
    //写入本地文件查看一下
    ImageIO.write(tempImage, "JPEG", new File(WebConn.SAVEPATH + "web" + i + ".jpg"));
    int iw = tempImage.getWidth();
    int ih = tempImage.getHeight();
   
    //将图像信息转化为二进制数组
    int []pix = new int[iw*ih];
    for (int j = 0; j < ih; j++) {
     for (int k = 0; k < iw; k++) {
        pix[j*(iw)+k] = tempImage.getRGB(k,j);
        if(pix[j*(iw)+k]==-1){
         pix[j*(iw)+k]=0;
        }else{
         pix[j*(iw)+k]=1;
        }
     }
    }
    int r = this.getMatchNum(pix);
    returnStr += (r + "");
   }
  } catch (IOException e) {
   e.printStackTrace();
  }  
 
  return returnStr;
 }
 
 
 /**
  * 将图像矩阵中的值与矩阵模版中的值对比
  * @param pix
  * @return
  */
 public int getMatchNum(int[] pix){
  int result = -1;
  int temp = 100;
  int x;
  //9个数据
  for(int k=0;k<=9;k++){
   x=0;
      for(int i=0;i<pix.length;i++){
       int matrixValue = NumberModel.value[k][i];
       int pixValue = pix[i];
       x = x + Math.abs(pixValue - matrixValue); 
      }
      //寻找相似度最高的
      //x值越小,相似度越高
      if(x < temp){
       temp = x;
       result = k;
      }
  }
  return result;
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值