Java使用Tessdata做OCR图片文字识别的详细思路
程序员文章站
2022-03-12 23:41:18
说到文字识别,目前除了用一些现成的api,大概就是 tessdata、canvas或者 ocrad等。1、百度接口用过(可以自己去百度开发者申请,免费的),识别率吧,还可以,但也不是百分百的,但是次数...
说到文字识别,目前除了用一些现成的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 = fsv.gethomedirectory(); // 这便是读取桌面路径的方法了 string url = com.getpath() + "/test"; file location = new file(url); if (!location.exists()) { location.mkdirs(); } string imgpath = location.getabsolutepath() + file.separator + "pic_" + time + ".jpg"; string cleanpath = location.getabsolutepath(); //存了原图片和清楚后图片的地址 string[] imgpath = { imgpath, cleanpath }; file targetfile = new file(imgpath); try { fileutils.copyfile(screen, targetfile); } catch (ioexception e1) { e1.printstacktrace(); } //元素图片路径 return imgpath; }
3、对截取图片进行处理:灰度化、二值化、去除干扰线等
以下是图像处理的类,其中对于去除干扰线的操作还是慎用,可能会把文字也剔除掉。
public class cleanelementimage { /** * * @param sfile * 需要去噪的图像 * @param destdir * 去噪后的图像保存地址 * @throws ioexception */ public static void handlimage(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); // } // } // } // } 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、准备识别的语言包
默认是英文(识别字母和数字),如果要识别中文(数字 + 中文),需要制定语言包。
语言包可以指定一个路径,有就可以了。
可以下载源码,然后到下面这个路径找到语言包,把语言包放到一个路径:
例如:xxx/tessdata/
下面。
tesseract.js-master.zip\tesseract.js-master\tests\assets\traineddata
5、对图片进行识别
/** * 图片识别 * @author wangy * @date 2019-08-26 * @param parameter */ public static string ocrresult(webelement element ) throws exception { filesystemview fsv = filesystemview.getfilesystemview(); file com=fsv.gethomedirectory(); //这便是读取桌面路径的方法了 string url = ""; string os = system.getproperty("os.name"); //识别系统,找不同的语言包路径 if (os.indexof("windows") == -1) { url = "/opt/google/"; } else { url = com.getpath(); } //获取元素截图的路径 string path[]=screenshot.elementscreenshot(element); //获取未处理的截图路径 string imgpath=path[0]; string result = null; file imagefile = new file(imgpath); //要对图片处理 cleanelementimage.handlimage(imagefile,path[1]); itesseract instance = new tesseract(); //读取语言包的路径地址 instance.setdatapath(url + file.separator + "test" + file.separator + "tessdata"); // 默认是英文(识别字母和数字),如果要识别中文(数字 + 中文),需要制定语言包,这里是数字,所以没用语言包 // instance.setlanguage("chi_sim"); //为了防止没截完图片就识别,做了一个简单的循环 try{ string ocrresult=instance.doocr(imagefile); if(imagefile.exists()&&ocrresult!=""){ result=ocrresult; }else { while(true){ thread.sleep(1000); if(imagefile.exists()&&ocrresult!=""){ result=ocrresult; break; } } } }catch(tesseractexception e){ system.out.println(e.getmessage()); } return result; }
这一部分由于项目问题,贴在这里做了特殊处理,原码有一点点区别。大家使用,如果有什么问题,欢迎反馈!
6、成果
这里简单放个对照,图片将就看一下效果,识别结果大概90%以上吧:
到此这篇关于java使用tessdata做ocr图片文字识别的详细思路的文章就介绍到这了,更多相关java tessdata图片文字内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!