本文主要是介绍oepncv 图像矫正,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//图像定位矫正
bool ImageLocal(cv::Mat srcImg, cv::Mat& warpImg, Point2f SrcAffinePts[])
{Mat grayImg;if (srcImg.channels() != 1){cvtColor(srcImg, grayImg, COLOR_BGR2GRAY);}else{grayImg = srcImg.clone();}Mat blurImg;medianBlur(grayImg, blurImg, 5);Mat binImg;threshold(blurImg, binImg, 10, 255, THRESH_BINARY);//namedWindow("binImg", WINDOW_NORMAL);//imshow("binImg", binImg);vector<vector<Point>>contours;findContours(binImg, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);RotatedRect bRect;for (int cnt = 0; cnt < contours.size(); cnt++){double area = contourArea(contours[cnt]);if (area > 1000){bRect = minAreaRect(contours[cnt]);}}if (bRect.size.empty())return false;//如果没有找到最小外接矩形,返回false//找到最小外接矩形四个顶点Point2f srcPoints[4];bRect.points(srcPoints);//for (int i = 0; i < 4; i++)//{// line(srcImg, srcPoints[i], srcPoints[(i + 1) % 4], Scalar(0, 255, 0), 3);//}//将四个点按照左上、右上、右下、左下进行区分int TL, TR, BR, BL;double addmax = 0.0, addmin = 999.9, submax = 0.0, submin = 999.9;for (int i = 0; i < 4; i++){double addval = srcPoints[i].x + srcPoints[i].y;double subval = srcPoints[i].x - srcPoints[i].y;if (addval > addmax){addmax = addval;BR = i;}if (addval < addmin){addmin = addval;TL = i;}if (subval > submax){submax = subval;TR = i;}if (subval < submin){submin = subval;BL = i;}}double LeftHeight = EuDis(srcPoints[TL], srcPoints[BL]);double RightHeight = EuDis(srcPoints[TR], srcPoints[BR]);double MaxHeight = max(LeftHeight, RightHeight);double UpWidth = EuDis(srcPoints[TL], srcPoints[TR]);double DownWidth = EuDis(srcPoints[BL], srcPoints[BR]);double MaxWidth = max(UpWidth, DownWidth);//这里使用的顺序是左上、右上、右下、左下顺时针顺序。SrcAffinePts、DstAffinePts要一一对应SrcAffinePts[0] = Point2f(srcPoints[TL]);SrcAffinePts[1] = Point2f(srcPoints[TR]);SrcAffinePts[2] = Point2f(srcPoints[BR]);SrcAffinePts[3] = Point2f(srcPoints[BL]);Point2f DstAffinePts[4] = { Point2f(0,0),Point2f(MaxWidth,0),Point2f(MaxWidth,MaxHeight),Point2f(0,MaxHeight) };Mat M = getPerspectiveTransform(SrcAffinePts, DstAffinePts);warpPerspective(srcImg, warpImg, M, Size(MaxWidth, MaxHeight), 1, 0, Scalar::all(0));return true;
}
这篇关于oepncv 图像矫正的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!