java做爬虫识别验证码的工具类,识别数字加字母的验证图片

使用java来做验证码识别,识别一些普通的验证码图片

最近公司要做爬虫
前言:
我们都知道,验证码的作用是用来验证你是否为机器人,基本是做反爬虫或刷数据的一类功能验证。针对这种情况,引用一位老人家的名言,“要用魔法打败魔法”,我们想爬别人数据只能通过更高明的技术。本文介绍的也不是啥高明的手段,毕竟只能识别一些简单的验证码,废话少说,直接上干货。

思路分析:
代码并不是我原创的,我只是一个裁缝,把别人的布自己拼一拼,再用点自己的线。验证码区分是否是机器和真人的方式就是在图片上加上一些干扰线,干扰机器的识别。

示例图片:
在这里插入图片描述
这些杂线干扰了机器的识别,BAT提供的云服务ocr识别不了。我们需要进行格式化,通过代码的操作后生成的图片为
在这里插入图片描述
去掉了干扰线以后在使用orc识别准确率基本到80%~90%了。但是机器容易自动识别出一些空格,有的杂线没有完全去除,导致识别出"、"," ` "等各种字符(例如示例验证码R下的、),所以我加了字符的过滤,只留下字母和数字。也有一些J会识别成 ] ,所以在过滤之前加一下判断,这个需要自己来加,我没有加。

ocr识别是引入的一个jar包,有防爬虫执行,识别几次后让你点击才能继续执行。针对这点可以把免费的jar包换位云服务的识别接口。

首先引入pom依赖

<!-- 获取并识别验证码-->
        <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.15</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.8.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>com.asprise.ocr</groupId>
            <artifactId>java-ocr-api</artifactId>
            <version>15.3.0.3</version>
        </dependency>

然后是工具类,工具类有两个方法,

package com.evaluation.train.common.util;


import com.asprise.ocr.Ocr;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.IOUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;

public class OCRCodeUtil {
    /**
     *  根据接口地址识别
     * @param netPath http链接
     * @param savePath 验证码图片保存到本地的位置
     * @param destDir 验证码可识别操作后的保存位置
     * @return
     * @throws IOException
     */
    public static String DictCode(String netPath, String savePath, String destDir) throws IOException {
        //把文件保存到本地地址
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(netPath);
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + getMethod.getStatusLine());
            return "Method failed: " + getMethod.getStatusLine();
        }
        String picName = savePath;
        File filepic = new File(picName);
        if (!filepic.exists())
            filepic.mkdir();
        String fileName = picName + new Date().getTime() + ".jpg";
        File filepicF = new File(fileName);
        InputStream inputStream = getMethod.getResponseBodyAsStream();
        OutputStream outStream = new FileOutputStream(filepicF);
        IOUtils.copy(inputStream, outStream);
        outStream.close();
        filepicF = new File(fileName);
        cleanLinesInImage(filepicF, destDir);
        Ocr.setUp(); // one time setup
        Ocr ocr = new Ocr(); // create a new OCR engine
        ocr.startEngine("eng", Ocr.SPEED_FASTEST); // English
        String code = ocr.recognize(new File[]{filepicF}, Ocr.RECOGNIZE_TYPE_TEXT, Ocr.OUTPUT_FORMAT_PLAINTEXT);
//        char[] chars = code.toCharArray();
//        for (int i = 0; i < chars.length; i++) {
//            switch (chars[i]) {
//                case ']':
//                    chars[i] = 'j';
//                    break;
//            }
//        }
//        code = chars.toString();
        code = code.replaceAll("[^0-9a-zA-Z]", "");
        ocr.stopEngine();
        return code;

    }

    /**
     * 根据本地路径识别
     *
     * @param sfile   识别的file
     * @param destDir 处理后放入的文件夹
     * @return
     * @throws IOException
     */
    public static String DictCode(File sfile, String destDir) throws IOException {
        cleanLinesInImage(sfile, destDir);
        File filepicF = new File(destDir + sfile.getName());
        Ocr.setUp(); // one time setup
        Ocr ocr = new Ocr(); // create a new OCR engine
        ocr.startEngine("eng", Ocr.SPEED_FASTEST); // English
        String code = ocr.recognize(new File[]{filepicF}, Ocr.RECOGNIZE_TYPE_TEXT, Ocr.OUTPUT_FORMAT_PLAINTEXT);
//        char[] chars = code.toCharArray();
//        for (int i = 0; i < chars.length; i++) {
//            switch (chars[i]) {
//                case ']':
//                    chars[i] = 'j';
//                    break;
//            }
//        }
//        code = chars.toString();
        code = code.replaceAll("[^0-9a-zA-Z]", "");
        ocr.stopEngine();
        return code;

    }

    /**
     * @param sfile   需要去噪的图像
     * @param destDir 去噪后的图像保存地址
     * @throws IOException
     */
    public static void cleanLinesInImage(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 = 1; y < h - 1; y++) {
            for (int x = 1; x < w - 1; x++) {
                boolean flag = false;
                if (isBlack(binaryBufferedImage.getRGB(x, y))) {
                    //左右均为空时,去掉此点
                    if (isWhite(binaryBufferedImage.getRGB(x - 1, y)) && isWhite(binaryBufferedImage.getRGB(x + 1, y))) {
                        flag = true;
                    }
                    //上下均为空时,去掉此点
                    if (isWhite(binaryBufferedImage.getRGB(x, y + 1)) && isWhite(binaryBufferedImage.getRGB(x, y - 1))) {
                        flag = true;
                    }
                    //斜上下为空时,去掉此点
                    if (isWhite(binaryBufferedImage.getRGB(x - 1, y + 1)) && isWhite(binaryBufferedImage.getRGB(x + 1, y - 1))) {
                        flag = true;
                    }
                    if (isWhite(binaryBufferedImage.getRGB(x + 1, y + 1)) && isWhite(binaryBufferedImage.getRGB(x - 1, y - 1))) {
                        flag = true;
                    }
                    if (flag) {
                        binaryBufferedImage.setRGB(x, y, -1);
                    }
                }
            }
        }


        // 矩阵打印
//        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;
    }
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值