最近看了篇文章,讲述的是单应性矩阵Homography matrix的理解与应用,尝试着运行文章中的代码时发现总是报异常。目前水平尚属于初级阶段的我花了一个下午的时间,还请了外援,现在终于解决了。
遇到的问题如下图所示。
将点由Point改为Point2f后这个问题得到了解决。
其他一些可能由于原作者手误敲错代码而引起的问题这里就不再提出。下面是改正后可运行的代码。
#include <opencv2\opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
using namespace std;
void main()
{
//读入广告图
Mat src = imread("timg2.jpg");
if (!src.data)
{
cout << "could not loag image..." << endl;
}
namedWindow("input image", CV_WINDOW_FREERATIO);
imshow("input image", src);
//读入用来替代广告图中某一广告牌的图片
Mat replaceImg = imread("1.jpg");
if (!replaceImg.data)
{
cout << "could not loag image..." << endl;
}
namedWindow("adv content", CV_WINDOW_FREERATIO);
imshow("adv content", replaceImg);
vector<Point2f> src_corners(4);
vector<Point2f> dst_corners(4);
//用来替换某一广告牌的图片四角坐标
src_corners[0]=Point2f(0.0, 0.0);
src_corners[1]=Point2f(replaceImg.cols, 0.0);
src_corners[2]=Point2f(0.0, replaceImg.rows);
src_corners[3]=Point2f(replaceImg.cols, replaceImg.rows);
//广告图中被替代广告牌的四角坐标
dst_corners[0] = Point2f(786, 517);
dst_corners[1] = Point2f(1018, 395);
dst_corners[2] = Point2f(799, 658);
dst_corners[3] = Point2f(1053, 605);
//计算单应性矩阵
Mat h = findHomography(src_corners, dst_corners);
//将用来替换广告牌的图像进行形状视角变换
Mat output_img;
warpPerspective(replaceImg, output_img, h, src.size());
//求掩膜
Mat m1 = Mat::zeros(replaceImg.size(), CV_8UC1);
m1 = Scalar(255);
Mat mask_output;
warpPerspective(m1, mask_output, h, src.size());
namedWindow("Mask Result", CV_WINDOW_FREERATIO);
imshow("Mask Result", mask_output);
//得到最终的结果并保存
Mat result1;
add(output_img, output_img, result1, mask_output);
Mat result2;
bitwise_not(mask_output, mask_output);
add(src, result1, result2,mask_output);
Mat result;
add(output_img, result2, result);
namedWindow("Final result", CV_WINDOW_FREERATIO);
imshow("Final result", result);
imwrite("result.png", result);
waitKey(0);
}
输入的广告图如下:
被用来替换广告图中某一广告牌的图像如下:
最终的替换效果图如下: