代码
public static void main(String[] args) {
OpencvTest2 opencvTest2 = new OpencvTest2();
//读入图片
Mat src = Imgcodecs.imread("F:\\opencvPhoto\\photo\\1-temp.jpg");
//灰度化
Mat gray = opencvTest2.gray(src);
//二值化
Mat adaptiveThreshold = opencvTest2.adaptiveThreshold(gray);
Imgcodecs.imwrite("F:\\opencvPhoto\\result\\adaptiveThreshold.jpg",src);
//膨胀+腐蚀:补全表格线内的空洞
Mat element = Imgproc.getStructuringElement(Imgproc.MORPH_RECT,new Size(3, 3));
Imgproc.dilate(adaptiveThreshold, adaptiveThreshold, element);
Imgproc.erode(adaptiveThreshold, adaptiveThreshold, element);
Imgcodecs.imwrite("F:\\opencvPhoto\\result\\dilateAndErode.jpg",src);
//获得横线
Mat horizontalLine =opencvTest2.getHorizontal(adaptiveThreshold.clone());
Imgcodecs.imwrite("F:\\opencvPhoto\\result\\horizontal.jpg",horizontalLine);
//获得竖线
Mat verticalLine =opencvTest2.getVertical(adaptiveThreshold.clone());
Imgcodecs.imwrite("F:\\opencvPhoto\\result\\vertical.jpg",verticalLine);
//横竖线合并
Mat tableLine = opencvTest2.getOr(horizontalLine, verticalLine);
Imgcodecs.imwrite("F:\\opencvPhoto\\result\\tableLine.jpg",tableLine);
}
/**
* 灰度化
* @param src 原图
* @return
*/
public Mat gray(Mat src){
Imgproc.cvtColor(src, src, Imgproc.COLOR_BGR2GRAY);
return src;
}
/**
* 自适应二值化
* @param src 灰度图
* @return
*/
public Mat adaptiveThreshold(Mat src){
Imgproc.adaptiveThreshold(src, src, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV , 3, 3);
return src;
}
/**
* 得到横线并进行延长
* @param adaptiveThreshold
* @return
*/
public Mat getHorizontal(Mat adaptiveThreshold){
int scale = 20; //这个值越大,检测到的直线越多
int horizontalsize = adaptiveThreshold.cols() / scale;
Mat horizontalStructure = Imgproc.getStructuringElement(Imgproc.MORPH_RECT
,new Size(horizontalsize, 1));
// 获得横线:先腐蚀再膨胀
Imgproc.erode(adaptiveThreshold, adaptiveThreshold, horizontalStructure);
Imgproc.dilate(adaptiveThreshold, adaptiveThreshold, horizontalStructure);
return adaptiveThreshold;
}
/**
* 得到竖线并进行相连
* @param adaptiveThreshold
* @return
*/
public Mat getVertical(Mat adaptiveThreshold){
int scale = 20; //这个值越大,检测到的直线越多
int verticalsize = adaptiveThreshold.rows() / scale;
if(verticalsize == 0) {
verticalsize = 1;
}
Mat verticalStructure = Imgproc.getStructuringElement(Imgproc.MORPH_RECT,new Size(1, verticalsize));
// 获得竖线:先腐蚀再膨胀
Imgproc.erode(adaptiveThreshold, adaptiveThreshold, verticalStructure);
Imgproc.dilate(adaptiveThreshold, adaptiveThreshold, verticalStructure);
return adaptiveThreshold;
}
/**
* 横竖线合并
* @param horizontal
* @param vertical
* @return
*/
public Mat getOr(Mat horizontal,Mat vertical){
Mat or=new Mat();
Core.bitwise_or(horizontal,vertical,or);
return or;
}
原图
二值化图
膨胀+腐蚀补全空洞
获得横线
获得竖线
横竖线合并获得表格线
参考链接
https://blog.csdn.net/yomo127/article/details/52045146?utm_source=blogxgwz1