# 一、图像平移

## 1.图像平移代码 （不改变图像大小）

``````#include<iostream>
#include<opencv.hpp>
using namespace std;
using namespace cv;

int main()
{
Mat img1;
imshow("原图", img1);
int r = img1.rows;
int c = img1.cols;
int x0 = 100;
int y0 = 100;

Mat img2(img1.size(), img1.type());
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
int x = j - x0;
int y = i - y0;

if (x >= 0 && y >= 0 && x < c&&y < r)
{
img2.at<Vec3b>(i, j) = img1.ptr<Vec3b>(y)[x];
}
}
}

imshow("不改变图像大小", img2);
waitKey(0);
}
``````

## 2.图像平移代码 （改变图像大小）

``````int main()
{
Mat img1;
imshow("原图", img1);

int x0 = 100;
int y0 = 100;

int r = img1.rows + y0;
int c = img1.cols + x0;

Mat img2(r,c, img1.type());
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
int x = j - x0;
int y = i - y0;

if (x >= 0 && y >= 0 && x < c&&y < r)
{
img2.at<Vec3b>(i, j) = img1.ptr<Vec3b>(y)[x];
}
}
}

imshow("改变图像大小", img2);
waitKey(0);
}
``````

# 二、图像旋转

## 1.图像旋转函数

opencv提供的getRotationMatrix2D函数来实现图像旋转，用来计算出旋转矩阵。

``````Mat getRotationMatrix2D(Point2f center, double angle, double scale)

center 旋转中心点
angle  旋转的角度
scale 图像缩放因子
``````

## 2.仿射变换函数

``````void warpAffine(InputArray src, OutputArray dst,
InputArray M, Size dsize,
int flags = INTER_LINEAR,
int borderMode = BORDER_CONSTANT,
const Scalar& borderValue = Scalar());
src 输入
dst 输出
M 变换矩阵
Size 尺寸
flags 插值算法标识符
borderMode 边界像素模式
borderValue 边界取值
``````

## 3.代码

``````int main()
{
Mat img1;

imshow("原图", img1);

Point center(img1.cols / 2, img1.rows / 2);

Mat m = getRotationMatrix2D(center, 30, 0.5);

Mat img2;

warpAffine(img1, img2, m, img1.size());

imshow("旋转", img2);

waitKey(0);

}
``````

# 三、图像缩放

## 1.图像缩放函数

``````void resize(InputArray src, OutputArray dst,
Size dsize, double fx = 0, double fy = 0,
int interpolation = INTER_LINEAR);
src 输入
dst 输出
dsize 尺寸
fx 在x轴缩放比例
fy 在y轴缩放比例
interpolation 插值方式
``````

## 2.图像缩小代码

``````int main()
{
Mat img1;

imshow("原图", img1);

Mat img2;

resize(img1, img2, Size(img1.cols / 2, img1.rows / 2));

imshow("缩小", img2);

waitKey(0);
}
``````

## 3.图像放大代码

``````int main()
{
Mat img1;

imshow("原图", img1);

Mat img2;

resize(img1, img2, Size(img1.cols * 2, img1.rows * 2));

imshow("放大", img2);

waitKey(0);
}
``````

THE END