欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaSE图像验证码简单识别程序详解

程序员文章站 2023-12-05 16:15:58
本文为大家分享了javase图像验证码简单识别程序,供大家参考,具体内容如下 首先你应该对图片进行样本采集,然后将样本进行灰度处理,也就是变成黑白两色。 然后你就可以使...

本文为大家分享了javase图像验证码简单识别程序,供大家参考,具体内容如下

首先你应该对图片进行样本采集,然后将样本进行灰度处理,也就是变成黑白两色。

然后你就可以使用该类,对目标文件进行分析。具体怎么实现我觉得这个类非常清楚,就是将样本从左都有这么横向移动,匹配出一个合适的就将坐标调整到下个位置。 

此程序已是3年多前写的,后来没有在深入写下去,图像识别一个很深的领域,得需要很深的数学功底跟思维能力,这个java的程序效率不高,也不能识别变形的或者拉伸的图片,但在那个年代,已经足够用了,大家如果有更好的开源的图像识别代码,请务必来信交流:)

/**
 * 图片解析引擎,适合做网站验证码的分析。
 * 首先必须载入样品,解析器将从左到右横向扫描,发现于样本的就自动记录。
 * 当然本程序不适合样本不是唯一的,也就是说要识别的图片被缩放或者坐标变动和变形本程序无法进行这样的识别。
 * 如果图片中的颜色变化非常大,此程序可能会有问题,当然了你可以选择一个标准的值做为转换成0,1矩阵的标准。
 * 
 * 样本的制作:请将样本转换成灰度模式,只含有两色最好,当然了不转换我也帮你转换了。
 * 
 */

import java.awt.image;
import java.awt.image.bufferedimage;
import java.io.file;
import java.util.arraylist;
import java.util.iterator;
import java.util.list;

import javax.imageio.imageio;

public class imageparser {

  // ------------------------------------------------------------ private data

  // 样本的矩阵
  private static list swatches   = null;

  // 样本的值
  private static list swatchevalues = null;

  // 图片文件的矩阵化
  private byte[][]  targetcolors;
  
  // ------------------------------------------------------------ test main method
  public static void main(string[] args) {
    // 加入样本与其样本对应的数值
    string[] files = new string[10];
    string[] values = new string[10];
    for (int i = 0; i < files.length; i++){
      files[i] = "d:/workspace/szxclientapp/res/" + i + ".jpg";
      values[i] = string.valueof(i);
    }
    
    imageparser parse = new imageparser(files, values);
    long startime = system.currenttimemillis();
    try {
      // 解析图片
      system.out.println(parse.parsevalue("d:/workspace/szxclientapp/res/validatenum"));
      long sincetime = system.currenttimemillis();
      system.out.println("所花时间 = " + (sincetime - startime));
    } catch (exception e) {
      e.printstacktrace();
    }
  }

  // ------------------------------------------------------------ constructors

  /**
   * 载入所有样本路径与其样本对应的数值
   * 
   * @param files
   */
  public imageparser(string[] files, string[] values) {
    // 只允许样本创建一次即可
    if (swatches == null && swatchevalues == null) {
      int fileslength = files.length;
      int valueslength = values.length;
      if(fileslength != valueslength){
        system.out.println("样本文件与样本数值不匹配!请重新设置!");
        return;
      }
      swatches = new arraylist(fileslength);
      swatchevalues = new arraylist(valueslength);
      int i = 0;
      try {
        for (; i < files.length; i++) {
          swatches.add(imagetomatrix(files[i]));
          swatchevalues.add(i, values[i]);
        }
      } catch (exception e) {
        system.out.println(files[i] + " can not be parsed");
        e.printstacktrace();
      }
    }
  }

  public imageparser() {
    super();
    if (swatches == null || swatchevalues == null) {
      system.out.println("您未载入样本,请先载入样本!");
    }
  }

  /**
   * 解析图片的值
   * 
   * @param parsefilepath
   *      给出图片路径
   * @return 返回字符串
   * @throws exception
   */
  public string parsevalue(string parsefilepath) throws exception {
    stringbuffer result = new stringbuffer();
    targetcolors = imagetomatrix(parsefilepath);
    // printmatrix(targetcolors);
    int height = targetcolors.length;
    int targetwidth = targetcolors[0].length;

    int width = 0;
    iterator it = swatches.iterator();
    while (it.hasnext()) {
      byte[][] bytes = (byte[][]) it.next();
      int templen = bytes[0].length;
      if (templen > width)
        width = templen;
    }
    // system.out.println("maxwidth = " + width);
    // system.out.println("maxheight = " + height);
    int xtag = 0;
    while ((xtag + width) < targetwidth) {
      cout: {
        iterator itx = swatches.iterator();
        int i = 0;
        while (itx.hasnext()) {
          byte[][] bytes = (byte[][]) itx.next();
          byte[][] temp = splitmatrix(targetcolors, xtag, 0, width, height);
          // system.out.println(i++);
          if (ismatrixinbigmatrix(bytes, temp)) {
            xtag += width;
            // system.out.println("new maxtrix: ");
            // printmatrix(temp);
            
            result.append(swatchevalues.get(i));
            break cout;
          }
          i++;
        }
        xtag++;
      }
    }
    return result.tostring();
  }

  // ------------------------------------------------------------ private methods

  /**
   * 判断一个矩阵是否在另外的矩阵中
   * 
   * @param source
   *      源矩阵
   * @param bigmatrix
   *      大的矩阵
   * @return 如果存在就返回 true
   */
  private static final boolean ismatrixinbigmatrix(byte[][] source, byte[][] bigmatrix) {
    if (source == bigmatrix)
      return true;
    if (source == null || bigmatrix == null)
      return false;

    if (source.length > bigmatrix.length)
      return false;

    try {
      for (int i = 0; i < source.length; i++) {
        if (source[i].length > bigmatrix[i].length)
          return false;
      }
    } catch (arrayindexoutofboundsexception e) {
      return false;
    }

    int height = source.length;
    int width = source[0].length;
    int x = 0, y = 0;
    int i = 0, j = 0;
    int count = 0;

    int comparecount = height * width;

    for (; i < bigmatrix.length - height + 1; i++) {
      for (j = 0; j < bigmatrix[i].length - width + 1; j++) {
        cout: {
          x = 0;
          count = 0;
          for (int k = i; k < height + i; k++) {
            y = 0;
            for (int l = j; l < width + j; l++) {
              // system.out.println("bytes[" + x + "][" + y + "]"
              // + " = " + source[x][y] + ", " + "other["
              // + k + "][" + l + "] = " + bigmatrix[k][l]);
              if ((source[x][y] & bigmatrix[k][l]) == source[x][y]) {
                count++;
              } else
                break cout;
              y++;
            }
            x++;
          }
          // system.out.println("count = " + count);
          if (count == comparecount)
            return true;
        }
      }
    }
    return false;
  }

  /**
   * 切割矩阵
   * 
   * @param source
   *      源矩阵
   * @param x
   *      x坐标
   * @param y
   *      y坐标
   * @param width
   *      矩阵的宽度
   * @param height
   *      矩阵的高度
   * @return 切割后的矩阵
   */
  private static final byte[][] splitmatrix(byte[][] source, int x, int y, int width, int height) {
    byte[][] resultbytes = new byte[height][width];
    for (int i = y, k = 0; i < height + y; i++, k++) {
      for (int j = x, l = 0; j < width + x; j++, l++) {

        resultbytes[k][l] = source[i][j];
        // system.out.println("source[" + i + "][" + j + "]" + " = " +
        // source[i][j] + ", " + "resultbytes["
        // + k + "][" + l + "] = " + resultbytes[k][l]);
      }

    }
    return resultbytes;
  }

  /**
   * 图片转换成矩阵数组
   * 
   * @param filepath
   *      文件路径
   * @return 返回矩阵
   * @throws exception
   *       可能会抛出异常
   */
  private byte[][] imagetomatrix(string filepath) throws exception {
    // 读入文件
    image image = imageio.read(new file(filepath));
    int w = image.getwidth(null);
    int h = image.getheight(null);
    bufferedimage src = new bufferedimage(w, h, bufferedimage.type_int_rgb);
    src.getgraphics().drawimage(image, 0, 0, null);

    byte[][] colors = new byte[h][w];

    for (int i = 0; i < h; i++) {
      for (int j = 0; j < w; j++) {
        int rgb = src.getrgb(j, i);
        // 像素进行灰度处理
        string sred = integer.tohexstring(rgb).substring(2, 4);
        string sgreen = integer.tohexstring(rgb).substring(4, 6);
        string sblank = integer.tohexstring(rgb).substring(6, 8);
        long ired = math.round((integer.parseint(sred, 16) * 0.3 + 0.5d));
        long igreen = math.round((integer.parseint(sgreen, 16) * 0.59 + 0.5d));
        long iblank = math.round((integer.parseint(sblank, 16) * 0.11 + 0.5d));
        long al = ired + igreen + iblank;

        // if (al > 127)
        // system.out.print(" " + " ");
        // else
        // system.out.print(" " + "1");
        // system.out.print(" " + (tempint > = maxint ? 0 : 1));
        // system.out.println("tempint = " + tempint);

        /* 将图像转换成0,1 */
        // 此处的值可以将来修改成你所需要判断的值
        colors[i][j] = (byte) (al > 127 ? 0 : 1);
      }
      // system.out.println();
    }

    return colors;
  }

  /**
   * 打印矩阵
   * 
   * @param matrix
   */
  private static final void printmatrix(byte[][] matrix) {
    for (int i = 0; i < matrix.length; i++) {
      for (int j = 0; j < matrix[i].length; j++) {
        if (matrix[i][j] == 0)
          system.out.print(" ");
        else
          system.out.print(" 1");
      }
      system.out.println();
    }
  }
}

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