基于轮廓发现矫正图片适用于表格类型图片,具体步如下:
1.边缘检测
2.寻找轮廓
3.找出匹配到的最大轮廓
4.获取轮廓内最大的矩形
5.获取矩形的四个顶点
6.得到旋转角度
7.矫正图片
/**
* 基于轮廓检测矫正图片,适用于表格类型图片
*/
@Test
public void testCorrect() {
Mat src = GeneralUtils.converMat("C:\\图片\\test\\0001.jpg");
//1.边缘检测
Mat cannyMat = new Mat();
Imgproc.Canny(src, cannyMat, 60, 200);
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();
//2.寻找轮廓
Imgproc.findContours(cannyMat, contours, hierarchy, Imgproc.RETR_EXTERNAL , Imgproc.CHAIN_APPROX_NONE , new Point(0 , 0));
//3.找出匹配到的最大轮廓
double area = Imgproc.boundingRect(contours.get(0)).area();
int index = 0;
List<Contour> contourList = new ArrayList<>();
for(int i = 0 ; i < contours.size() ; i++) {
double tempArea = Imgproc.boundingRect(contours.get(i)).area();
if (tempArea > 500) {
contourList.add(new Contour(tempArea, i));
} else {
continue;
}
if(tempArea > area) {
area = tempArea;
index = i;
}
}
//4.获取轮廓内最大的矩形
MatOfPoint2f matOfPoint2f = new MatOfPoint2f(contours.get(index).toArray());
RotatedRect rect = Imgproc.minAreaRect(matOfPoint2f);
//5.获取矩形的四个顶点
Point[] rectPoint = new Point[4];
rect.points(rectPoint);
//6.得到旋转角度
double angle = rect.angle + 90;
if (angle == 90) {
angle = 0.0;
}
//7.矫正图片
// 得到旋转矩阵算子
Point center = new Point();
center.x = src.cols() / 2.0;
center.y = src.rows() / 2.0;
Mat matrix = Imgproc.getRotationMatrix2D(center, -angle, 1);
// 旋转
Mat dst = new Mat();
Imgproc.warpAffine(src, dst, matrix, dst.size(), 1, 0, new Scalar(255, 255, 255));
GeneralUtils.saveByteImg(dst, "C:\\图片\\test\\correctImg.jpg");
}
《中医基础理论》