【 OpenCV】——图像平移
前言
本文介绍了图像平移的基础内容。
使用步骤
##1.引入库
#include<opencv2/opencv.hpp>
#include<opencv2/core/core.hpp>
#include<opencv2/imgcodecs.hpp>
#include<opencv2/highgui.hpp>
#include<opencv2\imgproc\types_c.h>
#include<iostream>
using namespace std;
using namespace cv;
## 2.读入数据
//平移改变大小
Mat fun(Mat &img, int xx, int yy)
{
int nrows = img.rows;
int ncols = img.cols;
Mat img1(img.size(), img.type());
//遍历图像
for (int i = 0; i < nrows; i++)
{
for (int j = 0; j < ncols; j++)
{
//映射变换
int x = j - xx;
int y = i - yy;
//边界判断
if (x >= 0 && y >= 0 && x < ncols&&y < nrows)
{
//把行y列x的img上的图像元素值复制到目标图像(i,j)位置上
img1.at<Vec3b>(i, j) = img.ptr<Vec3b>(y)[x];
}
}
}
return img1;
}
//平移不改变大小
Mat fun1(Mat &img, int xx, int yy)
{
int nrows = img.rows+abs(yy);
int ncols = img.cols+abs(xx);
Mat img1(nrows,ncols, img.type());
for (int i = 0; i < nrows; i++)
{
for (int j = 0; j < ncols; j++)
{
int x = j - xx;
int y = i - yy;
//边界判断
if (x >= 0 && y >= 0 && x < ncols&&y < nrows)
{
img1.at<Vec3b>(i, j) = img.ptr<Vec3b>(y)[x];
}
}
}
return img1;
}
int main()
{
Mat img;
//读取图像
img = imread("F:\\专高CV2\\图片\\520.jpg");
imshow("原图", img);
//向右平移
int xx = 50;
int yy = 80;
Mat img1 = fun(img, xx, yy);
imshow("平移改变大小1", img1);
Mat img2 = fun1(img, xx, yy);
imshow("平移不改变大小", img2);
//向左平移
int xx1 = -50;
int yy1 = -80;
Mat img3 = fun(img, xx1, yy1);
imshow("平移改变大小2", img3);
waitKey(0);
}
效果图展示
总结
以上是一个简单图片平移的代码段,读取一张图片,将图片进行向左、向右平移。