最近刚好学习到梯度方面的知识,所以上网查找了下关于梯度化一副图片的opencv代码,参考代码出自http://www.cnblogs.com/gnuhpc/archive/2012/06/28/2568755.html
#include<stdio.h>
#include<cv.h>
#include<highgui.h>
#include<math.h>
/*梯度化图片*/
int main()
{
IplImage* src=cvLoadImage("happycat.png",1);
CvPoint center;//定义一个二维坐标的点
int height = src ->height;
int width = src->width;
double scale=-3;
int row,col;
double dx,dy,weight;
uchar* ptr;
center = cvPoint(src->width/2,src->height/2);
cvNamedWindow("src",1);//显示原图
cvShowImage("src",src);
for(row=0;row<height;row++)
{
for(col=0;col<width;col++)
{
dx=(double) (col-center.x)/center.x;
dy=(double) (row-center.y)/center.y;
weight = exp((dx*dx+dy*dy)*scale);
/*可以使用opencv定义的宏来提取象素值,
假设灰度图像image,存取其i行j列的象素可以这样:CV_IMAGE_ELEM(image, uchar, i, j)
如果是彩色图像就是
CV_IMAGE_ELEM(image, uchar, i, 3*j)
CV_IMAGE_ELEM(image, uchar, i, 3*j+1)
CV_IMAGE_ELEM(image, uchar, i, 3*j+2) */
ptr=&CV_IMAGE_ELEM(src,uchar,row,col*3);
ptr[0]=cvRound(ptr[0]*weight);//将浮点数转化为整数;
ptr[1]=cvRound(ptr[1]*weight);
ptr[2]=cvRound(ptr[2]*weight);
}
}
cvSaveImage("grad.jpg",src,0);//保存图片
cvNamedWindow("grad",1);
cvShowImage("grad",src);//显示梯度化后的图片
cvWaitKey(0);
cvDestroyAllWindows();
cvReleaseImage(&src);
return 0;
}
效果如下: