参考文献:

http://www.cnblogs.com/self-control/archive/2013/01/18/2867022.html

http://opencv-code.com/tutorials/automatic-perspective-correction-for-quadrilateral-objects/

透视变换:

http://blog.csdn.net/xiaowei_cqu/article/details/26478135

具体流程为:

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

cv::Mat im = cv::imread(filename);

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)
{
    intx1 = a[0], y1 = a[1], x2 = a[2], y2 = a[3];
    intx3 = b[0], y3 = b[1], x4 = b[2], y4 = b[3];
 
    if(floatd = ((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;
        returnpt;
    }
    else
        returncv::Point2f(-1, -1);
}
  

  

1
2
3
4
5
6
7
8
9
10
std::vector<cv::Point2f> corners;
for
(
int i = 0; i < lines.size(); i++)
{
    for(intj = 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<cv::Point2f> 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<cv::Point2f>& corners, cv::Point2f center)
{
    std::vector<cv::Point2f> top, bot;
 
    for(inti = 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<cv::Point2f> 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);

  

 

 
// affine transformation.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h" /**
* Automatic perspective correction for quadrilateral objects. See the tutorial at
* http://opencv-code.com/tutorials/automatic-perspective-correction-for-quadrilateral-objects/
*/
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream> #pragma comment(lib,"opencv_core2410d.lib")
#pragma comment(lib,"opencv_highgui2410d.lib")
#pragma comment(lib,"opencv_imgproc2410d.lib") cv::Point2f center(0,0); cv::Point2f computeIntersect(cv::Vec4i a, cv::Vec4i b)
{
int x1 = a[0], y1 = a[1], x2 = a[2], y2 = a[3], x3 = b[0], y3 = b[1], x4 = b[2], y4 = b[3];
float denom; 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);
} void sortCorners(std::vector<cv::Point2f>& corners,
cv::Point2f center)
{
std::vector<cv::Point2f> 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]);
}
corners.clear(); if (top.size() == 2 && bot.size() == 2){
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.push_back(tl);
corners.push_back(tr);
corners.push_back(br);
corners.push_back(bl);
}
} int main()
{
cv::Mat src = cv::imread("image.jpg");
if (src.empty())
return -1; cv::Mat bw;
cv::cvtColor(src, bw, CV_BGR2GRAY);
cv::blur(bw, bw, cv::Size(3, 3));
cv::Canny(bw, bw, 100, 100, 3); std::vector<cv::Vec4i> lines;
cv::HoughLinesP(bw, lines, 1, CV_PI/180, 70, 30, 10); // Expand the lines
for (int i = 0; i < lines.size(); i++)
{
cv::Vec4i v = lines[i];
lines[i][0] = 0;
lines[i][1] = ((float)v[1] - v[3]) / (v[0] - v[2]) * -v[0] + v[1];
lines[i][2] = src.cols;
lines[i][3] = ((float)v[1] - v[3]) / (v[0] - v[2]) * (src.cols - v[2]) + v[3];
} std::vector<cv::Point2f> 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);
}
} std::vector<cv::Point2f> 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;
} // Get mass center
for (int i = 0; i < corners.size(); i++)
center += corners[i];
center *= (1. / corners.size()); sortCorners(corners, center);
if (corners.size() == 0){
std::cout << "The corners were not sorted correctly!" << std::endl;
return -1;
}
cv::Mat dst = src.clone(); // Draw lines
for (int i = 0; i < lines.size(); i++)
{
cv::Vec4i v = lines[i];
cv::line(dst, cv::Point(v[0], v[1]), cv::Point(v[2], v[3]), CV_RGB(0,255,0));
} // Draw corner points
cv::circle(dst, corners[0], 3, CV_RGB(255,0,0), 2);
cv::circle(dst, corners[1], 3, CV_RGB(0,255,0), 2);
cv::circle(dst, corners[2], 3, CV_RGB(0,0,255), 2);
cv::circle(dst, corners[3], 3, CV_RGB(255,255,255), 2); // Draw mass center
cv::circle(dst, center, 3, CV_RGB(255,255,0), 2); cv::Mat quad = cv::Mat::zeros(300, 220, CV_8UC3); std::vector<cv::Point2f> quad_pts;
quad_pts.push_back(cv::Point2f(0, 0));
quad_pts.push_back(cv::Point2f(quad.cols, 0));
quad_pts.push_back(cv::Point2f(quad.cols, quad.rows));
quad_pts.push_back(cv::Point2f(0, quad.rows)); cv::Mat transmtx = cv::getPerspectiveTransform(corners, quad_pts);
cv::warpPerspective(src, quad, transmtx, quad.size()); cv::imshow("image", dst);
cv::imshow("quadrilateral", quad);
cv::waitKey();
return 0;
}

实现结果:

OpenCV 透视变换实例的更多相关文章

  1. 对倾斜的图像进行修正——基于opencv 透视变换

    这篇文章主要解决这样一个问题: 有一张倾斜了的图片(当然是在Z轴上也有倾斜,不然直接旋转得了o(╯□╰)o),如何尽量将它纠正到端正的状态. 而要解决这样一个问题,可以用到透视变换. 关于透视变换的原 ...

  2. Java基于opencv—透视变换矫正图像

    很多时候我们拍摄的照片都会产生一点畸变的,就像下面的这张图 虽然不是很明显,但还是有一点畸变的,而我们要做的就是把它变成下面的这张图 效果看起来并不是很好,主要是四个顶点找的不准确,会有一些偏差,而且 ...

  3. android studio 使用 jni 编译 opencv 完整实例 之 图像边缘检测!从此在andrid中自由使用 图像匹配、识别、检测

    目录: 1,过程感慨: 2,运行环境: 3,准备工作: 4,编译 .so 5,遇到的关键问题及其解决方法 6,实现效果截图. (原创:转载声明出处:http://www.cnblogs.com/lin ...

  4. android studio 使用 jni 编译 opencv 完整实例 之 图像边缘检测!

    目录: 1,过程感慨: 2,运行环境: 3,准备工作: 4,编译 .so 5,遇到的关键问题及其解决方法 6,实现效果截图. ------------------------------------- ...

  5. opencv透视变换GetPerspectiveTransform的总结

    对于透视变换,必须为map_matrix分配一个3x3数组,除了3x3矩阵和三个控点变为四个控点外,透视变化在其他方面与仿射变换完全类似.具体可以参考:点击打开链接 主要用到两个函数WarpPersp ...

  6. opencv透视变换

    关于透视投影的几何知识,以及求解方法,可以参考 http://media.cs.tsinghua.edu.cn/~ahz/digitalimageprocess/chapter06/chapt06_a ...

  7. CentOS7 安装 OpenCV 的一些问题解决办法

    由于强迫症,实在受不了root权限的旧gcc才能使用boost而普通权限却是最新版gcc,经过一番折腾后,终于把配置全部弄好了,实际上就只需要把新版gcc的各个文件放到系统找到旧gcc的地方,并建立新 ...

  8. 最近学习工作流 推荐一个activiti 的教程文档

    全文地址:http://www.mossle.com/docs/activiti/ Activiti 5.15 用户手册 Table of Contents 1. 简介 协议 下载 源码 必要的软件 ...

  9. OpenCV】透视变换 Perspective Transformation(续)

    载分 [OpenCV]透视变换 Perspective Transformation(续) 分类: [图像处理] [编程语言] 2014-05-27 09:39 2776人阅读 评论(13) 收藏 举 ...

随机推荐

  1. 递归dict

    一个看起来非常酷的定义 class Example(dict): def __getitem__(self, item): try: return dict.__getitem__(self, ite ...

  2. python 3.3.3 字面量,正则,反斜杠和原始字符串

    两个不起眼但是比较重要的设定 Python str类型的字面量解释器 当反斜杠及其紧接字符无法构成一个具有特殊含义的序列('recognized escape sequences')时,Python选 ...

  3. Retrofit2.0 ,OkHttp3完美同步持久Cookie实现免登录(二)

    原文出自csdn: http://blog.csdn.net/sk719887916/article/details/51700659: 通过对Retrofit2.0的<Retrofit 2.0 ...

  4. android之View绘制

    Android系统的视图结构的设计也采用了组合模式,即View作为所有图形的基类,Viewgroup对View继承扩展为视图容器类,由此就得到了视图部分的基本结构--树形结构 View定义了绘图的基本 ...

  5. Eclipse 主题

    Eclipse开发环境默认都是白底黑字的,看到同事的Xcode中设置的黑灰色背景挺好看的,就去网络上查了一下.发现Eclipse也可以设置主题. http://eclipsecolorthemes.o ...

  6. 手把手教你轻松实现listview上拉加载

    上篇讲了如何简单快速的的实现listview下拉刷新,那么本篇将讲解如何简单快速的实现上拉加载更多.其实,如果你已经理解了下拉刷新的实现过程,那么实现上拉加载更多将变得轻松起来,原理完全一致,甚至实现 ...

  7. 【一天一道LeetCode】#122. Best Time to Buy and Sell Stock II

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Say you ...

  8. boost::bad_weak_ptr的原因

    出现boost::bad_weak_ptr最可能的原因是enable_shared_from_this<>类构造函数中调用shared_from_this(), 因为构造尚未完成,实例还没 ...

  9. Spark SQL官方文档阅读--待完善

    1,DataFrame是一个将数据格式化为列形式的分布式容器,类似于一个关系型数据库表. 编程入口:SQLContext 2,SQLContext由SparkContext对象创建 也可创建一个功能更 ...

  10. 使用js动态添加组件

    在文章开始之前,我想说两点 1 自己初学js,文章的内容在大神看来可能就是不值一提,但是谁都是从hello world来的,望高   手不吝指教# 2 我知道这个标题起的比较蛋疼,大家看图就能说明问题 ...