平时在拍照片时难免不小心把照片拍歪了,这时候可以使用透视变换矫正拍歪的照片!
效果
源代码
/******************************************************************************
* @brief : 使用透视变换矫正图片
* @usage : 用鼠标在原图上依次点击 左上-> 右上->右下->左下四个角点,
* 然后按回车,即可得的变换后的图像,变换后的图像会自动保存
* @author: QiDianMaker(1440657175@qq.com)
*****************************************************************************/
#include <iostream>
#include <string>
#include <cmath>
#include <opencv2/opencv.hpp>
using Points = cv::Point2f[4];
// 全局变量
Points src_points;
Points dst_points;
cv::Mat src, dst;
// 鼠标回调函数声明
void on_mouse(int event, int x, int y, int flags, void* ustc);
int main()
{
const std::string image_name{ "image.jpg" };
::src = cv::imread(image_name);
if (src.empty()) {
std::cerr << "could not load image...\n";
return -1;
}
cv::Mat src_copy;
::src.copyTo(src_copy);
cv::namedWindow("Input", cv::WINDOW_AUTOSIZE);
cv::setMouseCallback("Input", on_mouse, 0);
cv::imshow("Input", ::src);
cv::waitKey();
// 计算欧式距离
auto distance = [](cv::Point2f p1, cv::Point2f p2) -> float {
return std::hypotf((p1.x - p2.x), (p1.y - p2.y));
};
cv::Size2f dst_size(distance(src_points[0], src_points[1]),
distance(src_points[1], src_points[2]));
std::cout << "dst_size = " << dst_size << std::endl;
::dst_points[0] = cv::Point2f(0.0f, 0.0f);
::dst_points[1] = cv::Point2f(dst_size.width, 0.0f);
::dst_points[2] = cv::Point2f(dst_size.width, dst_size.height);
::dst_points[3] = cv::Point2f(0.0f, dst_size.height);
// 使用仿射变换
//cv::Mat warpMatrix = cv::getAffineTransform(::src_points, ::dst_points);
//cv::warpAffine(src_copy, ::dst, warpMatrix, dst_size);
// 使用透视变换
cv::Mat warp_matrix = cv::getPerspectiveTransform(::src_points, ::dst_points);
cv::warpPerspective(src_copy, ::dst, warp_matrix, dst_size,
cv::INTER_CUBIC, cv::BORDER_CONSTANT);
cv::imshow("Output", ::dst);
cv::imwrite("./out_" + image_name, ::dst);
std::cout << "Save successful!" << std::endl;
cv::waitKey();
}
void on_mouse(int event, int x, int y, int flags, void* ustc)
{
const auto point_color = cv::Scalar(0, 0, 255); // 红色
const auto line_color = cv::Scalar(0, 255, 0); // 绿色
static int idx = 0;
if (event == cv::EVENT_FLAG_LBUTTON) {
::src_points[idx] = cv::Point2i(x, y);
cv::circle(::src, ::src_points[idx], 2, point_color, 2, 2);
std::cout << "Point" << idx + 1 << ": " << src_points[idx] << std::endl;
if (idx > 0)
cv::line(::src, ::src_points[idx-1], ::src_points[idx], line_color, 2, 2);
if (idx == 3)
cv::line(::src, ::src_points[3], ::src_points[0], line_color, 2, 2);
cv::imshow("Input", ::src);
++idx;
}
}