【1】理論知識
圖像平移就是將圖像中所有的點按照指定的平移量水平或者垂直移動
【2】完整代碼
/*-------------------------------------------------------------------------------------------------------
*程序說明:
* 基於OpenCV實現------圖像的平移
*開發環境:
* win7+vs2010+opencv2.4.8
*創建時間地點:
* 陝西師範大學。2017.3.2
*參考資料:
* 《數字圖像處理與計算機視覺》張錚,徐超-----95頁算法
*作者:
* 李先生
--------------------------------------------------------------------------------------------------------*/
#include<opencv2\highgui\highgui.hpp>
#include<opencv2\highgui\highgui.hpp>
#include<opencv2\imgproc\imgproc_c.h>
#include<iostream>
using namespace cv;
using namespace std;
/*-----------------------------------【定義生成圖像的灰度直方圖】---------------------------------
*函數原型:
* void ImMove(IplImage* srcImage, IplImage* Image,int x,int y);
*函數功能:
* 圖像平移
*參數:
* IplImage* srcImage:要進行處理的灰度圖像
* IplImage* Image :將處理後的圖像寫入Image圖像
* int x : 表示水平方向移動的大小
* int y : 表示垂直方向移動的大小
*返回值:
無返回值類型
---------------------------------------------------------------------------------------------------------*/
void ImMove(IplImage* srcImage,IplImage* Image,int x,int y)
{
int nHeight = srcImage->height;
int nWidth = srcImage->width;
//判斷平移參數合理性
if(x>nWidth||y>nHeight)
{
cout<<"超過圖片大小"<<endl;
return ;
}
//開始遍歷原圖像,讀出每個位置的像素,並相應目標圖片所移動的中
//這裏需要注意的是圖像遍歷是從左上角開始的,即左上角位置的座標爲(0,0)
for(int h=0;h<nHeight;h++)
{
for(int w=0;w<nWidth;w++)
{
if(w+x<nWidth && h+y<nHeight) //判斷平移後的位置是否超出了原圖像的範圍
{
uchar gray= (uchar)*((uchar*)(srcImage->imageData+h*srcImage->widthStep)+srcImage->nChannels*w); //讀取原圖(w,h)座標的像素
*((uchar*)(Image->imageData+(h+y)*Image->widthStep)+Image->nChannels*(w+x)) = gray; //寫入目標目標圖片(w+x,h+y)座標
}
}
}
}
int main()
{
//【1】載入原圖
IplImage* srcImage = cvLoadImage("G:\\Image\\lenaRGB.png",0);
cvNamedWindow("原圖");
cvShowImage("原圖",srcImage);
//【2】爲目標圖片做準備
CvSize srcSize;
srcSize.height=srcImage->height;
srcSize.width=srcImage->width;
IplImage * Image=cvCreateImage(srcSize,srcImage->depth,1);
//【3】調用圖像平移函數並顯示結果
ImMove(srcImage,Image,50,100); //注:這裏直接給出移動的大小(50,100),即x向右移動50,同時向下移動100
cvNamedWindow("平移結果");
cvShowImage("平移結果",Image);
//【3】釋放內存空間
waitKey(0);
cvDestroyWindow("原圖");
cvDestroyWindow("平移結果");
cvReleaseImage(&srcImage);
cvReleaseImage(&Image);
return 0;
}
【3】運行結果