说到文字识别,目前除了用一些现成的api,大概就是 tessdata
、canvas
或者 ocrad
等。
1、百度接口用过(可以自己去百度开发者申请,免费的),识别率吧,还可以,但也不是百分百的,但是次数使用有限制,虽然也是够用,但是被限制总是害怕超过不让用。
2、canvas
的话是需要对图片做具体的处理,涉及到图片的翻转、置灰、文字间隔的设定等等,成功率很高,但是公司产品验证码是各式各样的,没办法用这种方法处理,所以暂时放弃了。
3、ocrad
这个目前用过其.js版本,识别率还是比较低的,具体使用后面会再写一篇文章介绍一下的。
虽然,网上对于 Tessdata
的技术介绍文章一搜一大片,但是其实小仙真正用起来的时候,还是费了点周折的。:fendou:
**思路:**截全图–截取元素图片–处理–识别–输出
注意:图片截取格式统一为.jpg,用png会出问题。
1、添加项目依赖
在项目的pom.xml文件中,添加以下依赖
<!--<tess4j图片识别>-->
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>2.0.1</version>
<exclusions>
<exclusion>
<groupId>com.sun.jna</groupId>
<artifactId>jna</artifactId>
</exclusion>
</exclusions>
</dependency>
2、从全图中截取元素图片
// 元素截图
public static String[] elementscreenShot(WebElement element )
throws Exception {
WrapsDriver wrapsDriver = (WrapsDriver) element;
long time = System.currentTimeMillis();
// 截图整个页面
File screen = ((TakesScreenshot) wrapsDriver.getWrappedDriver())
.getScreenshotAs(OutputType.FILE);
BufferedImage img = ImageIO.read(screen);
// 获得元素的高度和宽度
int width = element.getSize().getWidth();
int height = element.getSize().getHeight();
// 创建一个矩形使用上面的高度,和宽度
Rectangle rect = new Rectangle(width, height);
// 得到元素的坐标
Point p = element.getLocation();
BufferedImage dest = img.getSubimage(p.getX(), p.getY(),
(int) rect.getWidth(), (int) rect.getHeight());
// 存为png格式
ImageIO.write(dest, "png", screen);
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
FileSystemView fsv = FileSystemView.getFileSystemView();
File com = fs