如圖,將圖像中四邊形區域轉換爲矩形,並保存。
這裏用到幾何圖像變換中的透視變換。可以把上圖中的效果理解爲把左圖中的補丁單獨拿出保存,即摳補丁。當然如果是隻在原圖上保存四邊形區域周圍置零操作並沒對於後續其它圖像處理意義不大,因此將該區域保存爲矩形可以實現更多的圖像草圖。
參考以下資料進行學習,並對原代碼進行必要的簡單註釋,用getPerspectiveTransform()函數替換findHomography()計算轉換矩陣。
https://blog.csdn.net/liuphahaha/article/details/50719275
https://www.learnopencv.com/homography-examples-using-opencv-python-c/
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
struct userdata
{
Mat img;
vector<Point2f> points;
};
void mouseHandler(int event, int x, int y, int flags, void* data_ptr)
{
if (event == EVENT_LBUTTONDOWN)
{
userdata* data = ((userdata*)data_ptr);
circle(data->img, Point(x, y), 3, Scalar(0, 255, 255), 5);
imshow("Image_window", data->img);//用同一窗口取點畫點
if (data->points.size() < 4)
{
data->points.push_back(Point2f(x, y));
}
}
}
int main(int argc, char** argv)
{
//輸出目標矩形,和四個頂點。
//四個頂點是按環形順序排列的,因此在鼠標選點時也要對應環形取點
Mat outRect(360, 480, CV_8UC3);
vector<Point2f> dst_points;
dst_points.push_back(Point2f(0, 0));
dst_points.push_back(Point2f(outRect.cols, 0));
dst_points.push_back(Point2f(outRect.cols, outRect.rows));
dst_points.push_back(Point2f(0, outRect.rows));
Mat im_src = imread("D:/E/mypic/sh.jpg");
imshow("Image_window", im_src);
userdata data;
data.img = im_src.clone(); //不clone原圖就被畫點了
//set the callback function for any mouse event
setMouseCallback("Image_window", mouseHandler, &data);
waitKey(0);
// Mat warpMatrix = findHomography(data.points, dst_points);
Mat warpMatrix = getPerspectiveTransform(data.points, dst_points);
warpPerspective(im_src, outRect, warpMatrix, outRect.size(), INTER_LINEAR, BORDER_CONSTANT);
imwrite("outRect.jpg", outRect);//保存矩形圖片
imshow("outRect", outRect);
waitKey(0);
return 0;
}