【OpenCV】透视变换
接上篇
二 透视变换
透视变换是将图像投影到一个新的视平面,也称作投影映射。透视变换能提供更大的灵活性,但是一个透视投影并不是线性变换,因此其采用的是3X3的映射矩阵,控制点变为4个。
- Opencv中有封装好的透视变换函数:
void warpPerspective(InputArray src, OutputArray dst, InputArray M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())
- 生成变换矩阵的函数为:
Mat getPerspectiveTransform(const Point2f* src, const Point2f* dst)
-
实例
1 画出立方体
图片大小为600*600,立方体边长为300。
首先画出前面,各点坐标为(50,200),(350,200),(350,500),(50,500)。
然后画出上边四边形,坐标为(300,100),(550,100)。
最后画出右边四边形,坐标(550,320)。
2 上四边形透视变换
3 右四边形透视变换
- 透视变换程序
//透视变换源程序
#include <iostream>
#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
using namespace std;
int main()
{
Mat src_img(600, 600, CV_8UC3);
//读入图像
Mat img_1 = imread("F:/OpenCV_work/CV_AR/Task_2_Perspective/pic/2.jpg");
Mat img_2 = imread("F:/OpenCV_work/CV_AR/Task_2_Perspective/pic/1.jpg");
Mat img_3 = imread("F:/OpenCV_work/CV_AR/Task_2_Perspective/pic/3.jpg");
////正面图像嵌入
Mat roi_1 = src_img(Rect(50, 200, img_1.rows, img_1.cols));
Mat mask_1(roi_1.rows, roi_1.cols, roi_1.depth(), Scalar(1));
img_1.copyTo(roi_1, mask_1);
////上图像嵌入
Point2f src2_points[4] = { Point2f(0,300),Point2f(300,300),Point2f(300,0),Point2f(0,0)};
Point2f dst2_points[4] = { Point2f(0,100),Point2f(300,100),Point2f(500,0),Point2f(250,0)};
Mat M2 = getPerspectiveTransform(src2_points, dst2_points);
Mat dst_2;
Size size2(500, 100);
warpPerspective(img_2, dst_2, M2, size2);
Mat roi_2 = src_img(Rect(50, 100, dst_2.cols, dst_2.rows));
Mat mask_2(roi_2.rows, roi_2.cols, roi_2.depth(), Scalar(0));
dst_2.copyTo(roi_2, dst_2);
//右图像嵌入
Point2f src3_points[4] = { Point2f(0,0),Point2f(0,300),Point2f(300,0),Point2f(300,300)};
Point2f dst3_points[4] = { Point2f(0,100),Point2f(0,400),Point2f(200,0),Point2f(200,220) };
Mat M3 = getPerspectiveTransform(src3_points, dst3_points);
Mat dst_3;
Size size3(200, 400);
warpPerspective(img_3, dst_3, M3, size3);
Mat roi_3 = src_img(Rect(350, 100, dst_3.cols, dst_3.rows));
Mat mask_3(roi_3.rows, roi_3.cols, roi_3.depth(), Scalar(0));
dst_3.copyTo(roi_3, dst_3);
//正方形
line(src_img, Point(50, 500), Point(350, 500), Scalar(255, 0, 255), 1, CV_AA);
line(src_img, Point(50, 200), Point(350, 200), Scalar(255, 0, 255), 1, CV_AA);
line(src_img, Point(50, 200), Point(50, 500), Scalar(255, 0, 255), 1, CV_AA);
line(src_img, Point(350, 200), Point(350, 500), Scalar(255, 0, 255), 1, CV_AA);
//上四边形
line(src_img, Point(300, 100), Point(50, 200), Scalar(255, 0, 255), 1, CV_AA);
line(src_img, Point(300, 100), Point(550, 100), Scalar(255, 0, 255), 1, CV_AA);
line(src_img, Point(550, 100), Point(350, 200), Scalar(255, 0, 255), 1, CV_AA);
//右四边形
line(src_img, Point(550, 100), Point(550, 320), Scalar(255, 0, 255), 1, CV_AA);
line(src_img, Point(550, 320), Point(350, 500), Scalar(255, 0, 255), 1, CV_AA);
imshow("dst_2", dst_2);
imshow("dst_3", dst_3);
imshow("180121", src_img);
waitKey(0);
return 0;
}
欢迎指正!