版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36576377/article/details/79604813
void ImgCorrection(Mat imageSource)
{
Mat image;
imageSource.copyTo(image);
GaussianBlur(image, image, Size(3, 3), 0); //滤波
threshold(image, image, 100, 255, CV_THRESH_BINARY); //二值化
imshow("二值化", image);
Mat element = getStructuringElement(2, Size(7, 7)); //膨胀腐蚀核
dilate(image, image, element);
imshow("膨胀", image);
Mat image1;
Laplacian(image, image1, image.depth(), 1);//拉普拉斯变换寻找边界
imshow("边界", image1);
//寻找直线
vector<Vec2f>lines;
HoughLines(image1, lines, 1, CV_PI / 150, 60, 0, 0);
Mat DrawLine = Mat::zeros(image1.size(), CV_8UC1);
//Mat DrawLine = Mat::zeros(image1.size(), image1.type());
for (int i = 0; i<lines.size(); i++)
{
float rho = lines[i][0];
float theta = lines[i][1];
Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a*rho, y0 = b*rho;
pt1.x = cvRound(x0 + 1000 * (-b));
pt1.y = cvRound(y0 + 1000 * a);
pt2.x = cvRound(x0 - 1000 * (-b));
pt2.y = cvRound(y0 - 1000 * a);
line(DrawLine, pt1, pt2, Scalar(255), 1, CV_AA);
}
imshow("直线", DrawLine);
Point2f P1[4];
Point2f P2[4];
vector<Point2f>corners;
goodFeaturesToTrack(DrawLine, corners, 4, 0.1, 10, Mat()); //角点检测
cout << "角点坐标:" << endl;
for (int i = 0; i<corners.size(); i++)//四个角点的坐标
{
circle(DrawLine, corners[i], 3, Scalar(255), 3);
P1[i] = corners[i];
cout << corners[i].x << " " << corners[i].y << endl;
}
imshow("交点", DrawLine);
P2[0] = Point2f(0, 0);
P2[1] = Point2f(0, imageSource.rows);
P2[2] = Point2f(imageSource.cols, imageSource.rows);
P2[3] = Point2f(imageSource.cols, 0);
Mat elementTransf;
elementTransf = getAffineTransform(P1, P2);
warpAffine(imageSource, imageSource, elementTransf, imageSource.size(), 1, 0, Scalar(255));
imwrite("corrImge.jpg", imageSource);//校正后的图片保存
}