将两幅不同场景的图片使用透视变换进行坐标联动,选取两幅不同相机拍攝的图片,将原始图像中的坐标点与目标图像中的坐标点进行匹配对应。
//====================================================================//
//Created by JTY on 2022-5-16.
//Program:将原图中的坐标点转换到透视变换图中并与之对应
//Data:2022.5.16
//Author:JTY
//Version:V1.0
//====================================================================//
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
//首先读入图像
cv::Mat srcImage = cv::imread("E:/image/images/85.png", cv::IMREAD_GRAYSCALE);
//定义源标定点和目标标定点,源标定点为正常读入的图像的点,目标标定点为目标图与原始图的对应点
cv::Point2f srcPoints[4], dstPoints[4];
srcPoints[0] = cv::Point2f(190, 34);
srcPoints[1] = cv::Point2f(255, 33);
srcPoints[2] = cv::Point2f(199, 95);
srcPoints[3] = cv::Point2f(249, 95);
dstPoints[0] = cv::Point2f(149, 32);
dstPoints[1] = cv::Point2f(278, 32);
dstPoints[2] = cv::Point2f(155, 181);
dstPoints[3] = cv::Point2f(274, 181);
//1.求解变换矩阵
cv::Mat m_persctiveMat = cv::getPerspectiveTransform(srcPoints, dstPoints);//读入图像转换为目标图的矩阵
cv::Mat m_unPersctiveMat = cv::getPerspectiveTransform(dstPoints, srcPoints);//目标图到原始图像的转换矩阵
//2.求解目标图
cv::Mat dstImage;
cv::warpPerspective(srcImage, dstImage, m_persctiveMat, cv::Size(srcImage.cols, srcImage.rows), cv::INTER_LINEAR);
//3.求解其在原始图像上对应的坐标
//原始图上的四点
std::vector<cv::Point2f> rect;
rect.push_back(cv::Point2f(212, 66));
rect.push_back(cv::Point2f(212, 96));
rect.push_back(cv::Point2f(241, 64));
rect.push_back(cv::Point2f(241, 96));
std::vector<cv::Point2f> warpedRect;
cv::perspectiveTransform(rect, warpedRect, m_persctiveMat);
//4.可视化
cv::cvtColor(srcImage, srcImage, CV_GRAY2BGR);
cv::cvtColor(dstImage, dstImage, CV_GRAY2BGR);
rectangle(srcImage, Point(rect[0].x, rect[0].y), Point(rect[3].x, rect[3].y), cv::Scalar(0, 255, 0), 1, 8);
rectangle(dstImage, Point(warpedRect[0].x, warpedRect[0].y), Point(warpedRect[3].x, warpedRect[3].y), cv::Scalar(0, 255, 0), 1, 8);
for (int i = 0; i < 4; i++)
{
circle(srcImage, srcPoints[i], 2, Scalar(0, 0, 255), 2);
circle(dstImage, dstPoints[i], 2, Scalar(0, 0, 255), 2);
}
cv::imshow("srcImage", srcImage);
cv::imshow("dstImage", dstImage);
cv::waitKey(0);
return 0;
}