OpenCV 图形API(80)图像与通道拼接函数-----仿射变换函数warpAffine()

  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

对图像应用仿射变换。

函数 warpAffine 使用指定的矩阵对源图像进行变换:
dst ( x , y ) = src ( M 11 x + M 12 y + M 13 , M 21 x + M 22 y + M 23 ) \texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23}) dst(x,y)=src(M11x+M12y+M13,M21x+M22y+M23)

当设置了标志 WARP_INVERSE_MAP 时,使用上述公式。

否则,变换矩阵会先通过 invertAffineTransform 被求逆,然后才代入上面的公式中代替 M。

该函数不能在原地(in-place)操作。

函数原型

cpp 复制代码
GMat cv::gapi::warpAffine 	
(
 	const GMat &  	src,
	const Mat &  	M,
	const Size &  	dsize,
	int  	flags = cv::INTER_LINEAR,
	int  	borderMode = cv::BORDER_CONSTANT,
	const Scalar &  	borderValue = Scalar() 
) 		

参数

  • 参数 src:输入图像。
  • 参数 M:2×3 的变换矩阵。
  • 参数 dsize:输出图像的尺寸(宽度,高度)。
  • 参数 flags:
    插值方法的组合(参见 InterpolationFlags);
    可选标志 WARP_INVERSE_MAP,表示矩阵 M 是一个"逆变换"(即从目标图像映射到源图像,dst → src)。
  • 参数 borderMode:像素外推方法(参见 BorderTypes);
    不支持 BORDER_TRANSPARENT 模式。
  • 参数 borderValue:当边界模式为常量填充时所使用的像素值;
    默认值为 0(黑色)。

代码示例

cpp 复制代码
#include <opencv2/opencv.hpp>
#include <opencv2/gapi.hpp>
#include <opencv2/gapi/core.hpp>
#include <opencv2/gapi/imgproc.hpp>

using namespace cv;
using namespace cv::gapi;

int main() {
    // 加载输入图像
    Mat src = imread("/media/dingxin/data/study/OpenCV/sources/images/Lenna.png");
    if (src.empty()) {
        std::cerr << "无法加载图像!" << std::endl;
        return -1;
    }

    // 定义仿射变换矩阵 M
    // 示例:将图像旋转 45 度,并平移 (50, 50)
    double angle = 45; // 旋转角度
    double scale = 1;  // 缩放比例
    Point2f center(src.cols / 2.0, src.rows / 2.0); // 旋转中心
    Mat M = getRotationMatrix2D(center, angle, scale);
    // 添加平移
    M.at<double>(0, 2) += 50;
    M.at<double>(1, 2) += 50;

    // 定义输出图像尺寸
    Size new_size(src.cols, src.rows);

    // 定义 G-API 图像处理图(graph)
    GMat in;  // 输入节点

    // 应用仿射变换
    GMat out = gapi::warpAffine(in, M, new_size, INTER_LINEAR, BORDER_CONSTANT, Scalar(0, 0, 0));

    // 构建 GComputation
    GComputation computation(in, out);

    // 执行计算
    Mat dst;
    computation.apply(src, dst);

    // 显示结果
    imshow("原始图像", src);
    imshow("仿射变换后的图像", dst);
    waitKey();

    return 0;
}

运行结果

相关推荐
Moshow郑锴1 小时前
人工智能中的(特征选择)数据过滤方法和包裹方法
人工智能
TY-20252 小时前
【CV 目标检测】Fast RCNN模型①——与R-CNN区别
人工智能·目标检测·目标跟踪·cnn
CareyWYR3 小时前
苹果芯片Mac使用Docker部署MinerU api服务
人工智能
失散133 小时前
自然语言处理——02 文本预处理(下)
人工智能·自然语言处理
mit6.8243 小时前
[1Prompt1Story] 滑动窗口机制 | 图像生成管线 | VAE变分自编码器 | UNet去噪神经网络
人工智能·python
sinat_286945193 小时前
AI应用安全 - Prompt注入攻击
人工智能·安全·prompt
迈火4 小时前
ComfyUI-3D-Pack:3D创作的AI神器
人工智能·gpt·3d·ai·stable diffusion·aigc·midjourney
Moshow郑锴5 小时前
机器学习的特征工程(特征构造、特征选择、特征转换和特征提取)详解
人工智能·机器学习
CareyWYR6 小时前
每周AI论文速递(250811-250815)
人工智能
AI精钢6 小时前
H20芯片与中国的科技自立:一场隐形的博弈
人工智能·科技·stm32·单片机·物联网