作为代码界的菜鸟,最近在尝试着用vs实现《数字图像处理与机器视觉》一书中有关图像处理的VC++代码。目前先从简单的图像几何变换做起,希望能记录自己的成长^_^
本篇是图像平移变换的实现。
#include <iostream>
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
using namespace std;
using namespace cv;
/********************************************
void imMove(Mat img,Mat &dst,int x,int y)
功能: 平移图像
注: 图像范围不变
参数: Mat img:原图像
Mat dst: 处理后得到的图像
int x: 水平右移距离
int y: 垂直下移距离
返回值: 无
*********************************************/
void imMove(Mat img,Mat &dst, int x, int y)
{
int nHeight = img.rows;
int nWidth = img.cols;
int i, j;
if (x > nWidth || y > nHeight)
{
cout << "超出图片大小" << endl;
return;
}
for (i = 0; i < nHeight; i++)
{
for (j = 0; j < nWidth; j++)
{
if (i - x>0 && i - x<nHeight&&j - y>0 && j - y < nWidth)
dst.at<Vec3b>(i, j) = img.at<Vec3b>(i - x, j - y);
else
{
dst.at<Vec3b>(i, j)[0] = 0;
dst.at<Vec3b>(i, j)[1] = 0;
dst.at<Vec3b>(i, j)[2] = 0;
}
}
}
}
int main()
{
Mat img = imread("1.jpg");
Mat dst=img.clone();
imshow("原图", img);
//平移变换后
imMove(img,dst, 40, 60);
imshow("平移变换", dst);
waitKey(0);
return 0;
}
结果图如下: