赞
踩
参考博客链接:https://blog.csdn.net/liuphahaha/article/details/50719275
为了记录自己的学习:
OpenCV透视变化进行图像中的关键图提取(抠图)
上代码:
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
struct userdata {
Mat im;
vector<Point2f> points;
};
void mouseHandle(int event, int x, int y, int flags,void* ptr)
{
if (event == EVENT_LBUTTONDOWN)
{
userdata *data = (userdata*)ptr;
circle(data->im, Point(x, y), 3, Scalar(0, 0, 255), 3, CV_AA);
imshow("dst", data->im);
if (data->points.size() < 4)
{
data->points.push_back(Point2f(x, y));
}
}
}
int main()
{
Mat Image = imread("E:/Images/book1.jpg");
imshow("Image", Image);
Mat result = Mat::zeros(400, 300, CV_8UC3);
vector<Point2f> obj;
obj.push_back(Point2f(0, 0));
obj.push_back(Point2f(300, 0));
obj.push_back(Point2f(300, 400));
obj.push_back(Point2f(0, 400));
Mat dst = Image.clone();
userdata data;
data.im = dst;
imshow("dst", dst);
setMouseCallback("dst", mouseHandle, &data);
waitKey(0);
Mat H = findHomography(data.points, obj, CV_RANSAC);;
warpPerspective(Image, result, H, result.size());
imshow("result", result);
waitKey(0);
}
效果图如下:
原图:
结果图为:
OK!!!
换广告牌(抠图)
上代码:
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
struct userdata {
Mat im;
vector<Point2f> points;
};
void mouseHandle(int event, int x, int y, int flags,void* ptr)
{
if (event == EVENT_LBUTTONDOWN)
{
userdata *data = (userdata*)ptr;
circle(data->im, Point(x, y), 3, Scalar(0, 0, 255), 3, CV_AA);
imshow("dst", data->im);
if (data->points.size() < 4)
{
data->points.push_back(Point2f(x, y));
}
}
}
int main()
{
Mat Image = imread("E:/Images/photo1.jpg");
imshow("Image", Image);
vector<Point2f> obj;
obj.push_back(Point2f(0, 0));
obj.push_back(Point2f(Image.cols, 0));
obj.push_back(Point2f(Image.cols, Image.rows));
obj.push_back(Point2f(0, Image.rows));
Mat Image2 = imread("E:/Images/photo.jpg");
imshow("Image2", Image2);
Mat dst = Image2.clone();
userdata data;
data.im = dst;
imshow("dst", dst);
setMouseCallback("dst", mouseHandle, &data);
waitKey(0);
//将需要替换的图透视变换到大图进行变换
Mat H = findHomography(obj, data.points, CV_RANSAC);
warpPerspective(Image, dst, H, dst.size());
imshow("result", dst);
Point pts[4];
for (int i = 0; i < 4; i++)
{
pts[i] = data.points[i];
}
//进行填充(0,0,0)
fillConvexPoly(Image2, pts, 4, Scalar(0), CV_AA);
imshow("....", Image2);
//进行或操作
Image2 += dst;
imshow("finally", Image2);
imwrite("E:/Images/phototest.jpg", Image2);
waitKey(0);
}
原图:
模板图:
最后换好的图:
效果不错!!! 留着学习
欢迎关注微信公众号–木木夕算法笔记,与博主交流!
公众号会时不时更新有趣的图像算法哦!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。