图片验证码--BufferedImage 图片验证码去除干扰线

java-BufferedImage 图片验证码去除干扰线的方法( 用于OCR tesseract图像智能字符识别)

图片验证码自动识别的功能

网上对于初始图片的处理方法有去噪点、灰度化等,唯独难搜到去除干扰线的方法,可以比较干净地去除干扰线,提高OCR识别的准确率,“去除干扰线条“.

 

测试样板图片和数据:

 

 

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;


import javax.imageio.ImageIO;


public class CopyOfCleanLines {

      public static void main(String[] args) throws IOException  
        {    
            File testDataDir = File("F:\\ocr"); 
            final String destDir = testDataDir.getAbsolutePath()+"/tmp";  
            for (File file : testDataDir.listFiles())  
            {  
                cleanLinesInImage(file, destDir);  
                cleanLinesInImage(file, destDir); 
                cleanLinesInImage(file, destDir);
            }  
        }  

      /** 
         *  
         * @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;  
        }  
}

 

package com.gazgeek.helloworld.controller;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;


import javax.imageio.ImageIO;


public class CopyOfCleanLines {

    public static void main(String[] args) throws IOException
    {
        File testDataDir = new File("F:\\ocr");
        final String destDir = testDataDir.getAbsolutePath()+"/tmp";
        for (File file : testDataDir.listFiles())
        {
            cleanLinesInImage(file, destDir);
            cleanLinesInImage(file, destDir);
            cleanLinesInImage(file, destDir);
        }
    }

    /**
     *
     * @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;
    }
}

 

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生成图片验证码可以使用 JavaBufferedImage 类和 Graphics 类,以下是一个简单的示例代码: ```java import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.Random; public class ImageCode { private int width = 100; // 验证码图片的宽度 private int height = 40; // 验证码图片的高度 private int codeCount = 4; // 验证码字符个数 private int lineCount = 20; // 干扰线数量 private String code = null; // 验证码 private BufferedImage buffImg = null; // 验证码图片 private char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '2', '3', '4', '5', '6', '7', '8', '9'}; public ImageCode() { createImageCode(); } public void createImageCode() { int x = 0, fontHeight = 0, codeY = 0; int red = 0, green = 0, blue = 0; x = width / (codeCount + 2); fontHeight = height - 5; codeY = height - 8; buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.createGraphics(); Random random = new Random(); g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); Font font = new Font("Fixedsys", Font.BOLD, fontHeight); g.setFont(font); for (int i = 0; i < lineCount; i++) { int xs = random.nextInt(width); int ys = random.nextInt(height); int xe = xs + random.nextInt(width / 8); int ye = ys + random.nextInt(height / 8); red = random.nextInt(255); green = random.nextInt(255); blue = random.nextInt(255); g.setColor(new Color(red, green, blue)); g.drawLine(xs, ys, xe, ye); } StringBuilder randomCode = new StringBuilder(); for (int i = 0; i < codeCount; i++) { String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]); red = random.nextInt(255); green = random.nextInt(255); blue = random.nextInt(255); g.setColor(new Color(red, green, blue)); g.drawString(strRand, (i + 1) * x, codeY); randomCode.append(strRand); } code = randomCode.toString(); } public BufferedImage getBuffImg() { return buffImg; } public String getCode() { return code; } } ``` 使用时可以直接调用 `ImageCode` 类的 `getBuffImg` 方法获取生成的验证码图片,调用 `getCode` 方法获取验证码字符串。例如: ```java ImageCode imageCode = new ImageCode(); BufferedImage buffImg = imageCode.getBuffImg(); String code = imageCode.getCode(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值