我的个人博客:谋仁·Blog 微信公众号:谋仁的麻袋 CSDN:曹谋仁
Point2f类
图像由一个个像素点组成,我们为了存储每一个像素点,通常用Point类中(x,y)坐标来表示。Point2f表示Point类的两个数据x,y为float类型。 为了将原图中的某一块区域处理成鸟瞰图,我们首先要用Point2f来确定几个点来框定待处理区域。在这里,我们将要将一张斜放的扑克牌处理成鸟瞰图。故用四个点就足够确定其范围。 然后再建立一个Point2f类数组存放与原图框定区域对应的处理后的鸟瞰图在新窗口中的位置。相应代码:
Point2f srcPoint[4] = { {530,143},{773,193},{403,394}, {674,455} };
Point2f dstPoint[4] = { {0.0f,0.0f},{cardWidth,0.0f},{0.0f,cardHeight}, {cardWidth,cardHeight} };
getPerspectiveTransform函数
函数作用:根据输入和输出点获得图像透视变换的矩阵 重载一: 函数定义:
Mat getPerspectiveTransform(
const Point2f src[],
const Point2f dst[],
int solveMethod = DECOMP_LU
);
参数解释:
- src[]:输入点数组
- dst[]:输出点数组
- solveMethod:传递给cv::solve(DecompTypes) 解决一个或多个线性系统或最小二乘问题,DECOMP_LU是默认值。有关DecompTypes源代码是(解释已附在注释中):
enum DecompTypes {
DECOMP_LU = 0,
DECOMP_SVD = 1,
DECOMP_EIG = 2,
DECOMP_CHOLESKY = 3,
DECOMP_QR = 4,
DECOMP_NORMAL = 16
};
重载二函数定义:
Mat getPerspectiveTransform(
InputArray src,
InputArray dst,
int solveMethod = DECOMP_LU
);
warpPerspective函数
函数作用:对图像进行透视变换 函数定义:
void warpPerspective(
InputArray src,
OutputArray dst,
InputArray M,
Size dsize,
int flags = INTER_LINEAR,
int borderMode = BORDER_CONSTANT,
const Scalar& borderValue = Scalar()
);
参数解释:
- src:Mat类,输入图像
- dst:Mat类,透视变换后输出图像,与src数据类型相同
- M:透视变换矩阵
- dsize:输出图像大小
- flags:插值方法标志,源代码:
enum InterpolationFlags{
INTER_NEAREST = 0,
INTER_LINEAR = 1,
INTER_CUBIC = 2,
INTER_AREA = 3,
INTER_LANCZOS4 = 4,
INTER_LINEAR_EXACT = 5,
INTER_NEAREST_EXACT = 6,
INTER_MAX = 7,
WARP_FILL_OUTLIERS = 8,
WARP_INVERSE_MAP = 16
};
- borderMode:像素边界外推方法的标志,源代码:
enum BorderTypes {
BORDER_CONSTANT = 0,
BORDER_REPLICATE = 1,
BORDER_REFLECT = 2,
BORDER_WRAP = 3,
BORDER_REFLECT_101 = 4,
BORDER_TRANSPARENT = 5,
BORDER_REFLECT101 = BORDER_REFLECT_101,
BORDER_DEFAULT = BORDER_REFLECT_101,
BORDER_ISOLATED = 16
};
- Scalar& borderValue:边界的颜色设置,一般默认是0
示例
目的:将原图中斜放的?K进行透视变换得到鸟瞰图。 原图如下: 源代码:
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
#ifdef _DEBUG
#pragma comment(lib,"opencv_world453d.lib")
#else
#pragma comment(lib,"opencv_world453.lib")
#endif
int main()
{
Mat transMatrix, imgOut;
float cardWidth = 250;
float cardHeight = 350;
string path = "D:\\My Bags\\图片\\cards.jpg";
Mat imgIn = imread(path);
Point2f srcPoint[4] = { {530,143},{773,193},{403,394}, {674,455} };
Point2f dstPoint[4] = { {0.0f,0.0f},{cardWidth,0.0f},{0.0f,cardHeight}, {cardWidth,cardHeight} };
transMatrix = getPerspectiveTransform(srcPoint, dstPoint);
warpPerspective(imgIn, imgOut, transMatrix, Size(cardWidth, cardHeight));
imshow("原图", imgIn);
imshow("鸟瞰图", imgOut);
waitKey(0);
return 0;
}
运行结果: 原图 ?K鸟瞰图:
|