C++ 图像边界扩充函数copyMakeBorder

实验目的:将任意一张图片按其最长边扩展为正方形图片,使用三通道均值进行常数扩展:


1、Mat实现

//
int expandImg(
	const Mat  										srcImg,
	Mat											&dstImg)
{
	if(!srcImg.data || srcImg.channels()!=3){	
		cout<<"Can't open srcImg!"<< endl;
		return -1;
	}

	Mat imgClone = srcImg.clone();
	Mat blurImg;
	Scalar value;
	int exSide;
	int top, bottom, left, right;

	//中值滤波
	medianBlur(imgClone, blurImg, 3);

	//求得通道均值
	IplImage imgTmp = blurImg;
	IplImage *blurImgTemp = cvCloneImage(&imgTmp);
	CvScalar avgChannels = cvAvg(blurImgTemp);    
	double avgB = avgChannels.val[0];  
	double avgG = avgChannels.val[1];  
	double avgR = avgChannels.val[2];  
	value = Scalar(avgB, avgG, avgR);

	//按最长边计算左右或上下待扩充大小
	if(srcImg.cols <= srcImg.rows){
		top = 0; 
		bottom = 0;
		left = abs(srcImg.rows - srcImg.cols) / 2;
		right = abs(srcImg.rows - srcImg.cols) / 2;
	}else{
		top = abs(srcImg.rows - srcImg.cols) / 2;
		bottom = abs(srcImg.rows - srcImg.cols) / 2;
		left = 0;
		right = 0;
	}

	//
	copyMakeBorder( srcImg, dstImg, top, bottom, left, right, BORDER_CONSTANT, value );	
	
	imgClone.release();
	
	return 0;
}
这里,dstImg并未提前声明size,扩充过的size为srcImg的size加上top, bottom, left, right;


2、IplImage*实现:

IplImage * expandImg(
	IplImage * 										srcImg)
{
	if(!srcImg || srcImg->nChannels != 3 || srcImg->depth != IPL_DEPTH_8U){	
		cout<<"Can't open srcImg [expandImg()]!"<< endl;
		return NULL;
	}
	
	//
	CvScalar avgChannels;
	double avgB, avgG, avgR;
	int exwidth = 0, exheight = 0, exchannels = 0;
	
	//求得通道均值
	avgChannels = cvAvg(srcImg);    
	avgB = avgChannels.val[0];  
	avgG = avgChannels.val[1];  
	avgR = avgChannels.val[2];  

	//计算目标图像长宽
	if(srcImg->width <= srcImg->height){
		exwidth = srcImg->height;
		exheight = srcImg->height;
	}else{
		exwidth = srcImg->width;
		exheight = srcImg->width;
	}

	//
	exchannels = 3;
	IplImage* extendimg = cvCreateImage(cvSize(exwidth, exheight), IPL_DEPTH_8U, exchannels);	//目标扩充图像
	cvZero(extendimg);	//置0
	cvCopyMakeBorder(srcImg, extendimg, cvPoint(0,0), IPL_BORDER_CONSTANT, cvScalar(avgB, avgG, avgR));
	
	return extendimg;
}
这里,extendImg提前声明了size并置0,将srcImg放在extendImg的(0, 0)位置进行扩充;


参考:

在OpenCV中图像边界扩展 copyMakeBorder 的实现

图像变换 - 卷积边界(cvCopyMakeBorder)

opencv 边界填充 cvcopymakeborder


你可能感兴趣的:(图形图像,C/C++,计算机视觉,C++,图像处理)