【OpenCV】透视变换矫正

本文介绍如何使用OpenCV库实现图片的矫正与透视变换。通过运行程序,可以读取并显示图片尺寸,利用鼠标选取图片的四个关键点,进行矫正处理并展示矫正后的效果。代码中详细展示了如何获取图片的四个角点坐标,应用透视变换矩阵,完成图像的矫正。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

演示结果参考

 

功能实现:运行程序,会显示图片的尺寸,按回车键后,依次点击需矫正的图片的左上、右上、左下、右下角,并能显示其坐标,结果弹出矫正后的图片,如图上的PIC2对话框。可以继续选择图片四个点进行实验,按下字符'q'后退出。

 

代码如下:(注:图中的11.jpg图片自己选取放到该程序目录下。)

//使用鼠标在原图像上选取感兴趣区域
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
using namespace std;
using namespace cv;
const int N = 400;
const int M = 220;
Mat img;
Point p[5];
int flag = 1;
int cnt = 0;
static void mouse_callback(int event, int x, int y, int, void *) {
    //当鼠标左键按下时,记录其坐标
    if(event == EVENT_LBUTTONDOWN) {
        p[cnt].x = x*1.0; p[cnt++].y = y*1.0;
        cout << "p" << cnt << " is recorded at " << p[cnt-1] << endl;
    }

    if(cnt==4) {
            cnt=0;
            //变换前图像四个点
            vector<Point2f>src(4);
            src[0] = p[0];
            src[1] = p[1];
            src[2] = p[2];
            src[3] = p[3];
            //变换后
            vector<Point2f>dst(4);
            dst[0] = Point2f(0, 0);//左上
            dst[1] = Point2f(N, 0);//右上
            dst[2] = Point2f(0, M);//左下
            dst[3] = Point2f(N, M);//右下
            //获取透视变换矩阵

            Mat m = getPerspectiveTransform(src, dst);
            Mat res;
            
            warpPerspective(img, res, m, Size(N, M),INTER_LINEAR);//实现图像透视变换
            namedWindow("PIC2",1);
            imshow("PIC2", res);
            waitKey(0);
        }    

}
int main() {
    img = imread("11.jpg");
    if(!img.data) {cout<<"read image file wrong!"<<endl; getchar(); return 0;}
    cout << "height = " << img.size().height << ",width = " << img.size().width << endl;
    getchar();

    namedWindow("PIC");
    imshow("PIC", img);
    
    setMouseCallback("PIC", mouse_callback);//设置鼠标事件回调函数
    
    while(char(waitKey(1)) != 'q') {}

    return 0;
}

 

转载于:https://www.cnblogs.com/GraceSkyer/p/8585105.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值