图像缩放之双线性插值算法

代码:

#include "stdafx.h"
#include<cv.h>
#include<highgui.h>


void main(int argc, char * argv[])
{
	
	printf("%s\n",argv[1]);
	
	IplImage *pSrcImg = cvLoadImage(argv[1],CV_LOAD_IMAGE_COLOR);
	if(!pSrcImg)
	{
		printf("Load Image failed!\n");
		return ;
	}

	int dstImgHeight = 500; 
	int dstImgWidth = 500;
	
	IplImage *pDstImg = cvCreateImage(cvSize(dstImgWidth,dstImgHeight),pSrcImg->depth,3);
	
	unsigned char * srcImgData = (unsigned char *)pSrcImg->imageData;
	unsigned char * dstImgData = (unsigned char *)pDstImg->imageData;
	
	int srcImgHeight = pSrcImg->height;
	int srcImgWidth = pSrcImg->width;
	int srcImgWidthStep = pSrcImg->widthStep;
	int dstImgWidthStep = pDstImg->widthStep;

	float heightRatio = (float)dstImgHeight/(float)srcImgHeight;
	float widthRatio = (float)dstImgWidth/(float)srcImgWidth;

	for (int i=0;i<dstImgHeight;i++)
	{
		float fx = (float)i/heightRatio;
		int nx = (int)fx;
		int nxa1 = nx+1;
		float p = fx-nx; 
		if (nxa1>=srcImgHeight) //最后一行
		{
			nxa1 = srcImgHeight-1;
		}
		for (int j=0;j<dstImgWidth;j++)
		{
			float fy = (float)j/widthRatio;
			int ny = (int)fy;
			int nya1 = ny+1;
			float q = fy - ny;
			if (nya1>=srcImgWidth) //该行最后一个元素
			{
				nya1 = srcImgWidth -1;
			}

			float b = (1-p)*(1-q)*srcImgData[nx*srcImgWidthStep+ny*3];
			b += (1-p)*q*srcImgData[nx*srcImgWidthStep+nya1*3];
			b += p*(1-q)*srcImgData[nxa1*srcImgWidthStep+ny*3];
			b += p*q*srcImgData[nxa1*srcImgWidthStep+nya1*3];

			dstImgData[i*dstImgWidthStep+j*3]=(int)b;

			float g = (1-p)*(1-q)*srcImgData[nx*srcImgWidthStep+ny*3+1];
			g += (1-p)*q*srcImgData[nx*srcImgWidthStep+nya1*3+1];
			g += p*(1-q)*srcImgData[nxa1*srcImgWidthStep+ny*3+1];
			g += p*q*srcImgData[nxa1*srcImgWidthStep+nya1*3+1];

			dstImgData[i*dstImgWidthStep+j*3+1]=(int)g;

			float r = (1-p)*(1-q)*srcImgData[nx*srcImgWidthStep+ny*3+2];
			r += (1-p)*q*srcImgData[nx*srcImgWidthStep+nya1*3+2];
			r += p*(1-q)*srcImgData[nxa1*srcImgWidthStep+ny*3+2];
			r += p*q*srcImgData[nxa1*srcImgWidthStep+nya1*3+2];

			dstImgData[i*dstImgWidthStep+j*3+2]=(int)r;
		}
	}
	
	cvSaveImage("dstImg.bmp",pDstImg);
	cvNamedWindow("SrcImage",CV_WINDOW_AUTOSIZE);
	cvNamedWindow("DstImage",CV_WINDOW_AUTOSIZE);
	// 显示图像pSrc
	cvShowImage("SrcImage",pSrcImg);
	cvShowImage("DstImage",pDstImg);
	cvWaitKey(0);
	cvDestroyAllWindows();
	cvReleaseImage(&pSrcImg);
	cvReleaseImage(&pDstImg);
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值