# opencv系列之一 利用透视变换实现图像的俯视图（正视图）

a)载入图像→灰度化→边缘处理得到边缘图像（edge map）

cv::Mat gray;

cvtColor(im,gray,CV_BGR2GRAY);

Canny(gray,gray,100,150,3);

b)霍夫变换进行直线检测，此处使用的是probabilistic Hough transform（cv::HoughLinesP）而不是standard Hough transform（cv::HoughLines）

std::vector<Vec4i> lines;

cv::HoughLinesP(gray,lines,1,CV_PI/180,70,30,10);

for(int i = 0; i < lines.size(); i++)

line(im,cv::Point(lines[i][0],lines[i][1]),cv::Point(lines[i][2],lines[i][3]),Scalar(255,0,0),2,8,0);

c)通过上面的图我们可以看出，通过霍夫变换检测到的直线并没有将整个边缘包含，但是我们要求的是四个顶点所以并不一定要直线真正的相交，下面就要求四个顶点的坐标，公式为：

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 cv::Point2f computeIntersect(cv::Vec4i a, cv::Vec4i b) {     int x1 = a[0], y1 = a[1], x2 = a[2], y2 = a[3];     int x3 = b[0], y3 = b[1], x4 = b[2], y4 = b[3];       if (float d = ((float)(x1-x2) * (y3-y4)) - ((y1-y2) * (x3-x4)))     {         cv::Point2f pt;         pt.x = ((x1*y2 - y1*x2) * (x3-x4) - (x1-x2) * (x3*y4 - y3*x4)) / d;         pt.y = ((x1*y2 - y1*x2) * (y3-y4) - (y1-y2) * (x3*y4 - y3*x4)) / d;         return pt;     }     else         return cv::Point2f(-1, -1); } 

 1 2 3 4 5 6 7 8 9 10 std::vector corners; for (int i = 0; i < lines.size(); i++) {     for (int j = i+1; j < lines.size(); j++)     {         cv::Point2f pt = computeIntersect(lines[i], lines[j]);         if (pt.x >= 0 && pt.y >= 0)             corners.push_back(pt);     } }

d）检查是不是四边形
 1 2 3 4 5 6 7 8 9 std::vector approx; cv::approxPolyDP(cv::Mat(corners), approx,                  cv::arcLength(cv::Mat(corners), true) * 0.02, true);   if (approx.size() != 4) {     std::cout << "The object is not quadrilateral!" << std::endl;     return -1; }

e)确定四个顶点的具体位置（top-left, bottom-left, top-right, and bottom-right corner）→通过四个顶点求出映射矩阵来.
 void sortCorners(std::vector& corners, cv::Point2f center) {     std::vector top, bot;       for (int i = 0; i < corners.size(); i++)     {         if (corners[i].y < center.y)             top.push_back(corners[i]);         else             bot.push_back(corners[i]);     }       cv::Point2f tl = top[0].x > top[1].x ? top[1] : top[0];     cv::Point2f tr = top[0].x > top[1].x ? top[0] : top[1];     cv::Point2f bl = bot[0].x > bot[1].x ? bot[1] : bot[0];     cv::Point2f br = bot[0].x > bot[1].x ? bot[0] : bot[1];       corners.clear();     corners.push_back(tl);     corners.push_back(tr);     corners.push_back(br);     corners.push_back(bl); }

下面是获得中心点坐标然后利用上面的函数确定四个顶点的坐标

 for (int i = 0; i < corners.size(); i++)     center += corners[i];   center *= (1. / corners.size()); sortCorners(corners, center);

定义目的图像并初始化为0

 cv::Mat quad = cv::Mat::zeros(300, 220, CV_8UC3);

获取目的图像的四个顶点

 std::vector dst_pt; dst.push_back(cv::Point2f(0,0)); dst.push_back(cv::Point2f(quad.cols,0)); dst.push_back(cv::Point2f(quad.cols,quad.rows)); dst.push_back(cv::Point2f(0,quad.rows));

计算映射矩阵

 cv::Mat transmtx = cv::getPerspectiveTransform(corners, quad_pts);

 cv::warpPerspective(im, quad, transmtx, quad.size()); cv::imshow("quadrilateral", quad);