1 切边
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/328307d393c22de88ffe26304a4b927a.png)
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
using namespace std;
int main(int argc, char *argv[])
{
Mat sorImg = imread("6.jpg", IMREAD_UNCHANGED);
imshow("sor", sorImg);
Mat grayImg;
cvtColor(sorImg, grayImg, COLOR_BGR2GRAY);
Mat cannyImg;
Canny(grayImg, cannyImg, 20, 40);
imshow("cannyImg", cannyImg);
vector<vector<Point>> controus;
vector<Vec4i>ContourTree;
findContours(cannyImg, controus, ContourTree, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
int size = controus.size();
RotatedRect maxRotatedRect;
RotatedRect Rotatedrect;
for (int i = 0; i < size; ++i)
{
Rotatedrect = minAreaRect(controus[i]);
if (Rotatedrect.boundingRect().area() > maxRotatedRect.boundingRect().area())
{
maxRotatedRect = Rotatedrect;
}
}
Mat rotateImg;
float angle = maxRotatedRect.angle;
Mat kenerl = getRotationMatrix2D(Point2f(cannyImg.cols / 2, cannyImg.rows / 2), 360 + angle, 1);
warpAffine(sorImg, rotateImg, kenerl, sorImg.size(), INTER_LINEAR);
cvtColor(rotateImg, grayImg, COLOR_BGR2GRAY);
Canny(grayImg, cannyImg, 20, 40);
findContours(cannyImg, controus, ContourTree, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
size = controus.size();
Rect maxRect;
Rect rect;
for (int i = 0; i < size; ++i)
{
rect = boundingRect(controus[i]);
if (rect.area() > maxRect.area())
{
maxRect = rect;
}
}
Mat dstImg = rotateImg(maxRect);
imshow("dstImg", dstImg);
waitKey();
return 0;
}
2 寻找直线
2.1 Canny+霍夫变换(效果不好✖)
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
using namespace std;
Mat srcImage, dstImage;
Mat roiImage;
int curThresholdValue = 100;
int maxThresholdValue = 255;
void onDetectLines(int, void*);
int main(int argc, char** argv)
{
srcImage = imread("11.jpg", IMREAD_COLOR);
if (srcImage.empty())
{
cout << "error" << endl;
return -1;
}
namedWindow("原图:", WINDOW_AUTOSIZE);
imshow("原图:", srcImage);
namedWindow("检测直线:", WINDOW_AUTOSIZE);
Rect roi = Rect(10, 10, srcImage.cols - 20, srcImage.rows - 20);
roiImage = srcImage(roi);
imshow("ROI image", roiImage);
createTrackbar("threshold:", "检测直线:", &curThresholdValue, maxThresholdValue, onDetectLines);
onDetectLines(0, 0);
waitKey();
return 0;
}
void onDetectLines(int, void*)
{
Canny(srcImage, dstImage, curThresholdValue, curThresholdValue * 2, 3, false);
vector<Vec4i> lines;
HoughLinesP(dstImage, lines, 1, CV_PI / 180.0, 30, 30.0, 0);
cvtColor(dstImage, dstImage, COLOR_GRAY2BGR);
for (size_t t = 0; t < lines.size(); t++)
{
Vec4i ln = lines[t];
line(dstImage, Point(ln[0], ln[1]), Point(ln[2], ln[3]), Scalar(0, 0, 255), 2);
}
imshow("检测直线:"