您的位置:首页 > 其它

【VC图像处理】图像平移

2016-05-19 15:59 309 查看
#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

所以吧,注重每一个细节,特别是在边界!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: