提取ROI
1.通过trackbar获取thresh最佳值
#include "head.h"
// 1.边缘检测 + 轮廓发现或者直线检测最大外接矩形
// 2.二值分割 + 形态学方法 + hough直线找最大外接矩形
void findROI(int, void*);
Mat src, grayimg, dst;
const char* output = "final";
int maxvalue = 255;
int thresh = 150;
void qiebian()
{
src = imread("img/12.jpg");
namedWindow(output, CV_WINDOW_AUTOSIZE);
createTrackbar("threshold", output, &thresh, maxvalue, findROI);
findROI(0, 0);
waitKey(0);
}
void findROI(int ,void*)
{
cvtColor(src, grayimg, COLOR_BGR2GRAY);
Mat canny;
Canny(grayimg, canny, thresh, thresh * 2, 3, false);
vector<vector<Point>> contours;
vector<Vec4i> hireachy;
findContours(canny, contours, hireachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
int minw = src.cols*0.8;
int minh = src.rows*0.8;
RNG rng(12345);
for (int i = 0; i < contours.size(); i++)
{
//将轮廓中所有点contours[i]转换成rect
RotatedRect minRect = minAreaRect(contours[i]);
if (minRect.size.width > minw && minRect.size.height > minh && minRect.size.width<(src.cols-5))
{
Point2f pts[4];
minRect.points(pts);
Scalar color = Scalar(rng.uniform(0,255), rng.uniform(0, 255), rng.uniform(0, 255));
for (int j = 0; j < 4; j++)
{
line(src, pts[j], pts[(j + 1)%4], color, 2, 8, 0);
}
}
}
imshow(output, src);
}
2.确定thresh最佳值后直接提取感兴趣区域
void qiebian()
{
src = imread("img/12.jpg");
cvtColor(src, grayimg, COLOR_BGR2GRAY);
Canny(grayimg, grayimg, thresh, thresh * 2, 3, false);
vector<vector<Point>> conts;
vector<Vec4i> hireachy;
int h = src.rows*0.8;
int w = src.cols*0.8;
findContours(grayimg, conts, hireachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
for (int i = 0; i < conts.size(); i++)
{
RotatedRect rect = minAreaRect(conts[i]);
if (rect.size.height>h && rect.size.width>w && rect.size.width<(src.cols-5))
{
Rect finalRect = rect.boundingRect();
dst = src(finalRect);
imshow(output, dst);
break;
}
}
waitKey(0);
}
3.旋转角度调整