OpenCV 透視變換

平時在拍照片時難免不小心把照片拍歪了,這時候可以使用透視變換矯正拍歪的照片!

效果

源代碼

/******************************************************************************
 * @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;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容