首页 > 编程语言 >java_slenium_tess4j 简单图片识别

java_slenium_tess4j 简单图片识别

时间:2022-11-18 17:36:28浏览次数:40  
标签:slenium tess4j java String element instance File new png

1.导包


2.下载语言库

3.代码
1》直接识别图片

方法一:
// @param path : "C:\\Users\\Administrator\\Desktop\\下载\\03.png"
public static String IdentifyCode01(String path){
        String result = "";
        File imsge = new File(path);
        ITesseract instance = new Tesseract();
        //文件名称一定要是tessdata
        instance.setDatapath(TESSDATA);
        instance.setLanguage("eng");//英文厍识剂墩李比较准确
        instance.setLanguage("chi_sim");//如果要使用中文包,加上
        try {
            result = instance.doOCR(imsge).replace("\n","");
        } catch (TesseractException e) {
            e.printStackTrace();
        }
        System.out.println("IdentifyCode01 " + result);
        return result;
    }

方法二:

 public static String IdentifyCode(String path) {
        File imageFile = new File(path);
        ITesseract instance = new Tesseract();
        instance.setDatapath(TESSDATA);
        instance.setLanguage("eng");//英文厍识剂墩李比较准确
        instance.setLanguage("chi_sim");//如果要使用中文包,加上
        //图片二值化,增加识别率
        BufferedImage grayImage = null;
        try {
            grayImage = ImageHelper.convertImageToBinary(ImageIO.read(imageFile));
            //  grayImage = ImageHelper.convertImageToBinary(ImageIO.read(new File(TESSDATA)));
        } catch (IOException e2) {

            e2.printStackTrace();
        }
        try {
            // ImageIO.write(grayImage, "png", new File(System.getProperty("user.dir") + "/img", "vc1.png"));
            ImageIO.write(grayImage, "png", new File(path));

        } catch (IOException e1) {
            e1.printStackTrace();
        }
        // String path1 = System.getProperty("user.dir") + "/img/vc1.png";
        String path1 = path;

        File imageFile1 = new File(path1);


        String result = null;
        try {
            result = instance.doOCR(imageFile1);
        } catch (TesseractException e1) {
            e1.printStackTrace();
        }
        result=result.replaceAll("[^a-z^A-Z^0-9]", "");
        System.out.println("方法IdentifyCode: " + result);
        return result;
    }

2》下载图片

    /**
     * <p>Description(描述):   截图 保存 图片
     * </p>
     * @Title(标题): doOCR方法
     * @Company(公司): 
     * @Author(创建者): wqj(吴启俊)  Mobile:13311859332  E-mail:[email protected]   WeChat(QQ):799139357
     * @Type :
     * @Date(创建时间): 2022-11-18 16:26:27
     * @param driver :
     * @param element :
     * @return : void(返回值)
     *@throws:
     *@warn(警告):
     *copyright(版权): wqj(吴启俊)
     */
    private static void downloadPicture01(WebDriver driver,WebElement element) throws Exception {

        System.out.println("获取整页屏幕截图" + element.getText());
        //获取整页屏幕截图
        File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        BufferedImage fullImg = ImageIO.read(screenshot);

        //获取元素在页面上的位置
        Point point = element.getLocation();
        //获取元素的宽度和高度
        int eleWidth = element.getSize().getWidth();
        int eleHeight = element.getSize().getHeight();

        //裁剪整个页面截图以仅获取元素截图
        BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),
                eleWidth, eleHeight);
        ImageIO.write(eleScreenshot, "png", screenshot);
        //清空保存文件夹
        DeleteCacheAndFile.deleteChildren("C:\\Users\\Administrator\\Desktop\\Download01");
        //获取到当前时间戳
        Long l = System.currentTimeMillis();
        //生成4位随机数
        Integer i =(Integer)new Random().nextInt(9999);
        //将元素截图复制到磁盘
        // long imageName = ToolUtil.getNowUTC();
        // File screenshotLocation = new File("C:\\Screen",imageName+".png");
        File screenshotLocation = new File("C:\\Users\\Administrator\\Desktop\\Download01","--imageName"+".png");
        FileUtils.copyFile(screenshot, screenshotLocation);
    }

    /**
     * <p>Description(描述):  下载图片到本地         路劲下载 只能下载固定路径(完整路径,包括图片名称的路径)的图片
     * </p>
     * @Title(标题): downloadPicture方法
     * @Company(公司):
     * @Author(创建者): wqj(吴启俊)  Mobile:13311859332  E-mail:[email protected]   WeChat(QQ):799139357
     * @Type :
     * @Date(创建时间): 2022-11-18 16:29:43
     * @param urlList : [urlList图片地址,
     * @param path : path本地地址]     "C:\Users\Administrator\Desktop\Download01\--imageName.png"
     * @return : void(返回值)
     *@throws:
     *@warn(警告):
     *copyright(版权): wqj(吴启俊)
     */
    public static void downloadPicture(String urlList, String path) {

        URL url = null;
        try {
            //获取到当前时间戳
            Long l = System.currentTimeMillis();
            //生成4位随机数
            Integer i =(Integer)new Random().nextInt(9999);
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2》直接截图识别

/**
   *
   * @param driver  驱动器
   * @param element  需要处理的图片 元素位置对象 WebElement element = driver.findElement(By.id("codeImg"));
   * @return
   * @throws Exception
   */
  private static String doOCR(WebDriver driver,WebElement element) throws Exception {

      System.out.println("获取整页屏幕截图" + element.getText());
      //获取整页屏幕截图
      File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      BufferedImage fullImg = ImageIO.read(screenshot);

      //获取元素在页面上的位置
      Point point = element.getLocation();
      //获取元素的宽度和高度
      int eleWidth = element.getSize().getWidth();
      int eleHeight = element.getSize().getHeight();

      //裁剪整个页面截图以仅获取元素截图
      BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),
              eleWidth, eleHeight);
      ImageIO.write(eleScreenshot, "png", screenshot);
      //清空保存文件夹
      DeleteCacheAndFile.deleteChildren("C:\\Users\\Administrator\\Desktop\\Download01");
      //将元素截图复制到磁盘
      // long imageName = ToolUtil.getNowUTC();
      // File screenshotLocation = new File("C:\\Screen",imageName+".png");
      File screenshotLocation = new File("C:\\Users\\Administrator\\Desktop\\Download01","--imageName"+".png");
      FileUtils.copyFile(screenshot, screenshotLocation);

      //识别验证码
      ITesseract instance = new Tesseract();//调用Tesseract
      String tesspath = System.getProperty("user.dir");
      //  instance.setDatapath(tesspath + "/src/test/resources/tessdata");//进行读取,默认是英文,如果要使用中文包,加上
      instance.setDatapath(TESSDATA);

      instance.setLanguage("eng");//英文厍识剂墩李比较准确
      instance.setLanguage("chi_sim");//如果要使用中文包,加上
      String code = instance.doOCR(screenshotLocation);
      System.out.println("qqqqqqqqqqqqqq---"+code);
      return code;
  }

注意:TESSDATA :是语言库的地址。
如果需要,jar,语言库,留言,免费提供。整理的有的急,马上下班了!

标签:slenium,tess4j,java,String,element,instance,File,new,png
From: https://www.cnblogs.com/wqj-grh/p/16903976.html

相关文章

  • 8. 使Web工程依赖于Java工程
    #在pro02-maven-web工程的pom.xml文件下,添加对pro01-maven-java工程的依赖:(通过坐标) #添加测试代码:##在pro02-maven-web工程的src目录下,添加文件夹:test/java/com/at......
  • kmp算法(Java)
    详解参考:KMP算法讲解next数组求法方式1移动位数=已匹配的字符数-对应的部分匹配值已知空格与D不匹配时,前面六个字符"ABCDAB"是匹配的。查表可知,最后一个匹......
  • java构造方法的作用
    构造方法作用就是对类进行初始化。如果你没有定议任何构造方法的形式,程式会为你取一个不带任何参数的构造函数,那么你产生类的对像时只能用不带参数的方法,如:classa{}//没......
  • JavaScript代码是怎么在浏览器里面运行起来的?
    JavaScript代码是怎么在浏览器里面运行的?下面简单探索一下浏览器内核浏览器内核(RenderingEngine),常见的叫法如:排版引擎、解释引擎、渲染引擎,现在流行称为浏览器内核。......
  • JavaScript_对象_RegExp2与JavaScript_对象_RegExp3
    JavaScript_对象_RegExp2正则对象:1.创建 1.varreg  =new RegExp(“正则表达式”);2.var......
  • java 文件读写操作
    一、BufferedWriter写入文件+BufferedReader读取文件缓冲字符(BufferedWriter)是一个字符流类来处理字符数据。不同于字节流(数据转换成字节),你可以直接写字符串,数组或字符......
  • JavaScript_对象_Math与JavaScript_对象_RegExp1
    JavaScript_对象_MathMath:数学1.创建特点:Math对象不用创建,直接使用。Math.方法名();2.方法random()返回0~1之间的随机数含0不含......
  • Java 8 Stream基础操作汇总
    Java8Stream操作汇总目录Java8Stream操作汇总1.分组2.分组统计3.分组求和4.最大最小值5.排序前提条件://User实体类@DatapublicclassUser{/**......
  • 自定义IE表达式使用.tld文件减少jsp文件中的java代码时出现的错误(可运行)cvc-id.3
    tld类型的文件产生错误如下:但是不影响运行。只需要如下:将j--->J就行。原因知晓,若有大佬知晓,欢迎留言。本人看到后,必将改正 ......
  • Java进阶篇——设计模式
    设计模式一、代理模式使用代理类对真实对象进行代理,包括真实对象方法的调用、功能的扩展等。访问的时候也只能访问到代理对象,既保护了真实对象同时可以在原始对象上进行......