这篇文章主要为大家详细介绍了opencv实现图像平移,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了opencv实现图像平移的具体代码,供大家参考,具体内容如下
图像平移指的是沿水平方向或垂直方向进行图像的移动。
平移变换公式:
对于原始图像而言,正变换矩阵:
对于目标图像而言,逆变换矩阵:
代码:
#include<opencv2/imgproc.hpp>
#include<opencv2/highgui.hpp>
#include<opencv2/core.hpp>
#include<iostream>
#include<stdlib.h>
using namespace std;
using namespace cv;
Mat imgTranslation1(Mat& src, int xOffset, int yOffset);
Mat imgTranslation2(Mat& src, int xOffset, int yOffset);
int main()
{
Mat src = imread("C:\\Users\\H\\Desktop\\niao.bmp");
if (src.empty())
{
cout << "请检查图像是否存在..." << endl;
return -1;
}
pyrDown(src, src);
cout << "原图尺寸\trows:" << src.rows << "\tcols: " << src.cols << endl;
int xOffset = 50, yOffset = 80;
Mat dst1 = imgTranslation1(src, xOffset, yOffset);
imshow("dst1", dst1);
cout << "平移不改变尺寸\trows: " << dst1.rows << "\tcols: " << dst1.cols << endl;
Mat dst2 = imgTranslation2(src, xOffset, yOffset);
imshow("dst2", dst2);
cout << "平移改变尺寸\trows: " << dst2.rows << "\tcols: " << dst2.cols << endl;
waitKey(0);
system("pause");
return 0;
}
图像的平移 ,大小不变
Mat imgTranslation1(Mat& src, int xOffset, int yOffset)
{
int nrows = src.rows;
int ncols = src.cols;
Mat dst(src.size(), src.type());
for (int i = 0; i < nrows; i++)
{
for (int j = 0; j < ncols; j++)
{
映射变换
int x = j - xOffset;
int y = i - yOffset;
边界判断
if (x >= 0 && y >= 0 && x < ncols && y < nrows)
{
dst.at<Vec3b>(i, j) = src.ptr<Vec3b>(y)[x];
}
}
}
return dst;
}
//图像平移大小改变
Mat imgTranslation2(Mat& src, int xOffset, int yOffset)
{
int nrows = src.rows + abs(yOffset);
int ncols = src.cols + abs(xOffset);
Mat dst(nrows, ncols, src.type());
for (int i = 0; i < nrows; i++)
{
for (int j = 0; j < ncols; j++)
{
int x = j - xOffset;
int y = i - yOffset;
if (x >= 0 && y >= 0 && x < ncols && y < nrows)
{
dst.at<Vec3b>(i, j) = src.ptr<Vec3b>(y)[x];
}
}
}
return dst;
}结果展示:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
沃梦达教程
本文标题为:opencv实现图像平移
猜你喜欢
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- C++ 数据结构超详细讲解顺序表 2023-03-25
- ubuntu下C/C++获取剩余内存 2023-09-18
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- Easyx实现扫雷游戏 2023-02-06
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- Qt计时器使用方法详解 2023-05-30
- C语言qsort()函数的使用方法详解 2023-04-26
- C语言详解float类型在内存中的存储方式 2023-03-27
