OPENCV 基于旋转矩阵 旋转Point2f

发布于:2025-09-03 ⋅ 阅读:(19) ⋅ 点赞:(0)

测试效果

创建两个点,让第二个点绕第一个点转45度

代码解析

Mat a; a = imread("D:\\0.bmp", -1);

读取一张图片当作背景板

Point2f p1(350, 150); Point2f p2(550.0f, 150.0f);

创建两个点

cv::Mat mat = getRotationMatrix2D(p1, 45, 1.0);

生成旋转矩阵,中心点为p1

std::vector<cv::Point2f> points = { p2 }; cv::Mat srcPoint(points);

将p2的数据放进一个mat对象中

cv::Mat dstPoint; // 应用变换 cv::transform(srcPoint, dstPoint, mat);

创建结果Mat 执行矩阵变换

float x = dstPoint.at<float>(0, 0); float y = dstPoint.at<float>(0, 1); cv::Point2f rotatedPoint(x, y);

输出结果也是一个Mat对象 从这个Mat对象中取出仿射变换之后的点坐标数据

std::cout << "Rotated Point: " << rotatedPoint << std::endl; circle(mergedImage, p1, 3, Scalar(0, 255, 0), 3, LINE_AA); circle(mergedImage, p2, 3, Scalar(0, 255, 0), 3, LINE_AA); circle(mergedImage, rotatedPoint, 3, Scalar(0, 0, 255), 3, LINE_AA); line(mergedImage,p1,p2, Scalar(0, 255, 255),2,LINE_AA); line(mergedImage, p1, rotatedPoint, Scalar(0, 0, 255), 2, LINE_AA);

三个点坐标数据,绘制到图像上,以便确认执行正确。

原始代码

    Mat a;
    a = imread("D:\\0.bmp", -1);

    cv::Mat mergedImage;
    std::vector<cv::Mat> channels = { a, a, a };
    cv::merge(channels, mergedImage);


    Point2f p1(350, 150);
    Point2f p2(550.0f, 150.0f);

    cv::Mat mat = getRotationMatrix2D(p1, 45, 1.0);

    std::vector<cv::Point2f> points = { p2 };
    cv::Mat srcPoint(points);

    cv::Mat dstPoint;

    // 应用变换
    cv::transform(srcPoint, dstPoint, mat);

    // 提取结果
    float x = dstPoint.at<float>(0, 0);
    float y = dstPoint.at<float>(0, 1);
    cv::Point2f rotatedPoint(x, y);

    std::cout << "Rotated Point: " << rotatedPoint << std::endl;

    circle(mergedImage, p1, 3, Scalar(0, 255, 0), 3, LINE_AA);
    circle(mergedImage, p2, 3, Scalar(0, 255, 0), 3, LINE_AA);
    circle(mergedImage, rotatedPoint, 3, Scalar(0, 0, 255), 3, LINE_AA);

    line(mergedImage,p1,p2, Scalar(0, 255, 255),2,LINE_AA);
    line(mergedImage, p1, rotatedPoint, Scalar(0, 0, 255), 2, LINE_AA);


    imshow("1", mergedImage);
    waitKey();


网站公告

今日签到

点亮在社区的每一天
去签到