2. 把一幅图像进行平移。

实验二
#include "cv.h"
#include<stdio.h> 
#include "highgui.h"
IplImage *PingYi(IplImage *src, int h0, int w0);
int main(int argc, char** argv)
{

    IplImage* pImg; //声明IplImage指针
    IplImage* pImgAfterMove;
    pImg = cvLoadImage("6013202130.jpg");
    pImgAfterMove = cvCloneImage(pImg);
    cvSetZero(pImgAfterMove);
    pImgAfterMove = PingYi(pImg, 100, -100);

    cvNamedWindow("原图", CV_WINDOW_AUTOSIZE);
    cvShowImage("原图", pImg);
    cvNamedWindow("移动后", CV_WINDOW_AUTOSIZE);
    cvShowImage("移动后", pImgAfterMove);
    cvWaitKey(0); //等待按键

    cvDestroyWindow("aa");//销毁窗口
    cvDestroyWindow("bb");
    cvReleaseImage(&pImg); //释放图像
    cvReleaseImage(&pImgAfterMove);
    return 0;
}

//该函数的功能是实现图像的平移
//规定向下、向右为(正,正)
IplImage *PingYi(IplImage *src, int h0, int w0)
{
    int h = h0;
    int w = w0;
    int imageHeight = src->height;
    int imageWidth = src->width;
    int i, j;
    CvScalar sTemp;
    IplImage *dst = cvCloneImage(src);
    cvSetZero(dst);
    if (h >= 0 && w >= 0)
    {
        //
        for (i = 0; i<imageHeight - h; i++)
        {
            for (j = 0; j<imageWidth - w; j++)
            {
                sTemp = cvGet2D(src, i, j);
                cvSet2D(dst, i + h, j + w, sTemp);
            }
        }
    }
    else if (h<0 && w >= 0)
    {
        for (i = -h; i<imageHeight; i++)
        {
            for (j = 0; j<imageWidth - w; j++)
            {
                sTemp = cvGet2D(src, i, j);
                cvSet2D(dst, i + h, j + w, sTemp);
            }
        }
    }
    else if (h >= 0 && w<0)
    {
                for (i = 0; i<imageHeight - h; i++)
        {
            for (j = -w; j<imageWidth; j++)
            {
                sTemp = cvGet2D(src, i, j);
                cvSet2D(dst, i + h, j + w, sTemp);
            }
        }
    }
    else if (h<0 && w<0)
    {
                for (i = -h; i<imageHeight; i++)
        {
            for (j = -w; j<imageWidth; j++)
            {
                sTemp = cvGet2D(src, i, j);
                cvSet2D(dst, i + h, j + w, sTemp);
            }
        }
    }
    else
    {
        printf("无法移动哦!");
        dst = cvCloneImage(src);
    }
    return dst;

原文地址:https://www.cnblogs.com/zhangfeionline/p/5465175.html