最近弄了一个验证码图片识别的功能,效果还不错……
/**
* 图片处理类
*
*/
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;
}
}