【VC图像处理】图像平移

#include "opencv2/core/core.hpp"
#include"opencv2/highgui/highgui.hpp"
#include<opencv2/opencv.hpp>
#include "iostream"
using namespace std;
using namespace cv;
void Translation(Mat img,Mat &outImg,int lxoffset,int lyoffset);
 
void main()
{
	Mat SrcImg=imread("C:\\Users\\Administrator\\Desktop\\工作\\testp\\01.jpg",0);
	if(!SrcImg.data)
		cout<<"读取图片错误\n";


	Mat ResultImg1;
	Translation(SrcImg,ResultImg1,1,1);
	imshow("translation",ResultImg1);

	imshow("src",SrcImg);
	waitKey(0);

}
   /* img为输入图像,单通道
	outimg为输出图像,需有内存空间
	lxoffset为x偏移距离
	lyoffset为y偏移距离
	白色补充空出来的区域*/
void Translation1(Mat img,Mat outImg,int lxoffset,int lyoffset)
{
	int i,j;
	int Height=img.rows;
	int Width=img.cols ;//int Width=img.cols*img.channels();
	for(i=0;i<Height;i++)
	{
		uchar*out_data=outImg.ptr<uchar>(i);
		if(((i-lxoffset)>0)&&((i-lxoffset)<Height))
	    {
		 uchar*src_data=img.ptr<uchar>(i-lxoffset);
		 for(j=0;j<Width;j++)
		   {
			if(((j-lyoffset)>=0)&&(j-lyoffset<Width) ) 
			out_data[j]=src_data[j-lyoffset];
			else
				out_data[j]=255;
		   }
	     }
		else
			for(j=0;j<Width;j++)
				out_data[j]=255;
	}

}

void Translation(Mat img,Mat &outImg,int lxoffset,int lyoffset)
{
	int Height=img.rows;
	int Width=img.cols;
	outImg.create(Height,Width,img.type());
	for(int i=0;i<Height;i++)
		for(int j=0;j<Width;j++)
		{
			if((j-lxoffset<0)||(j-lxoffset>Width)||((i-lyoffset)<0)||((i-lyoffset)>Height))
			{
				if(img.channels()==1)
					outImg.at<uchar>(i,j)=255;
				else if(img.channels()==3)
					outImg.at<Vec3b>(i,j)=Vec3b(255,255,0);
			}
			else
			{
				if(img.channels()==1)
					outImg.at<uchar>(i,j)=img.at<uchar>(i-lyoffset,j-lxoffset);
				else if(img.channels()==3)
					outImg.at<Vec3b>(i,j)=img.at<Vec3b>(i-lyoffset,j-lxoffset);
			}
		}
}

 
 

代码还有一定的问题,下面的那个代码当取负值的时候内存报错,不造为啥

请教了薛学长!!他看了下 说>=Width.... 我试了下果真可以!!!学长太牛逼了,,,他说要注意细节,养成习惯 !确实啊,敲代码必修这样子,否则会死的很惨。。就比如今天那个读取图片,我之前从来不检查是否读取正确,今天把一个图片01.jpg写成了o1.jpg  检查了好久就是内存报错   以后养成良好的习惯吧

 对于上面的错误,很不明显。。。上面的if判断是反过来的   平常我们判断是   j-lxo>=0&&j-lxo<Width     所以当反过来的时候就应该是j-lxo<0  ||  j-lxo>=Width    

所以吧,注重每一个细节,特别是在边界!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值