java调用opencv身份证号识别

2,130 阅读1分钟

一、实现思路

1.矫正图片 这个可以参考上篇文章 Java调用opencv图片矫正

2.因为身份证大小是固定的 这里可以按照比例截取身份证号的区域

3.把截取图像用tess4j进行识别

4.效果图

image.png

二、部分代码

2.1图片剪辑

public static Mat cutRect(Mat image) {
Mat clone=image.clone();
Mat src=image.clone();

Imgproc.GaussianBlur(clone, clone, new Size(3, 3), 0, 0);
HighGui.imshow("GaussianBlur1", clone);

Imgproc.cvtColor(clone, clone,Imgproc.COLOR_BGR2GRAY);
HighGui.imshow("GRY1", clone);

int lowThresh=20;
//边缘检测
Imgproc.Canny(clone, clone,lowThresh, lowThresh*3,3);
HighGui.imshow("Canny1", clone);

List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();

// 寻找轮廓
Imgproc.findContours(clone, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);
System.out.println("轮廓:"+contours.size());
// 找出匹配到的最大轮廓
double area = Imgproc.boundingRect(contours.get(0)).area();
int index = 0;

// 找出匹配到的最大轮廓
for (int i = 0; i < contours.size(); i++) {
    double tempArea = Imgproc.boundingRect(contours.get(i)).area();
    if (tempArea > area) {
        area = tempArea;
        index = i;
    }
}

MatOfPoint2f matOfPoint2f = new MatOfPoint2f(contours.get(index).toArray());

RotatedRect rect = Imgproc.minAreaRect(matOfPoint2f);

Mat temp = new Mat(src , rect.boundingRect());
Mat t = new Mat();
temp.copyTo(t);

HighGui.imshow("cut", temp);
return t;
}

2.2身份证提取位置 参考

public static String card(Mat mat){
    Point point1=new Point(mat.cols()*0.34,mat.rows()*0.80);
    Point point2=new Point(mat.cols()*0.34,mat.rows()*0.80);
    Point point3=new Point(mat.cols()*0.89,mat.rows()*0.91);
    Point point4=new Point(mat.cols()*0.89,mat.rows()*0.91);
    List<Point> list=new ArrayList<>();
    list.add(point1);
    list.add(point2);
    list.add(point3);
    list.add(point4);
    Mat card= shear(mat,list);
    card=ImageUtil.drawContours(card,50);
    HighGui.imshow("card", card); 
  //高斯滤波
  	Imgproc.cvtColor(card, card,Imgproc.COLOR_BGR2GRAY);
  	Imgproc.GaussianBlur(card, card, new Size(3, 3), 0, 0);
  	Imgproc.threshold(card, card, 165, 255, Imgproc.THRESH_BINARY);
	 //Imgproc.Canny(image, image,lowThresh, lowThresh*3,3);
    System.out.println(ImageUtil.getImageMessage(Mat2BufImg(card,".jpg"),"eng"));
    return null;
}

2.3图片数字识别 tess4j

语言包的下载

pom

<dependency>
  <groupId>net.sourceforge.tess4j</groupId>
  <artifactId>tess4j</artifactId>
  <version>4.5.4</version>
</dependency>
public static String getImageMessage(BufferedImage img,String language){
    String result="";
    try{
        ITesseract instance = new Tesseract();
        instance.setTessVariable("user_defined_dpi", "300");
        //语言包的位置
        File tessDataFolder = new File("E:\\tessdata-master");
        instance.setLanguage(language);
        instance.setDatapath(tessDataFolder.getAbsolutePath());
        result = instance.doOCR(img);
        System.out.println(result);
    }catch(Exception e){
    	e.printStackTrace();
    }
    return result;
}