图像缩放之最近邻插值

来源:互联网 发布:cocos2dx程序员工资 编辑:程序博客网 时间:2024/05/20 22:35

基于OpenCV的代码:

#include "stdafx.h"#include<cv.h>#include<highgui.h>void main(int argc, char * argv[]){printf("%s\n",argv[1]);IplImage *pSrcGrayImg = cvLoadImage(argv[1],CV_LOAD_IMAGE_GRAYSCALE);if(!pSrcGrayImg){printf("Load Image failed!\n");return ;}    int dstImgHeight,dstImgWidth;//scanf("%d%d",&dstImgHeight,&dstImgWidth);dstImgHeight = 500;dstImgWidth = 500;IplImage *pDstGrayImg = cvCreateImage(cvSize(dstImgWidth,dstImgHeight),pSrcGrayImg->depth,1);int srcImgHeight,srcImgWidth;srcImgHeight = pSrcGrayImg->height;srcImgWidth = pSrcGrayImg->width;float heightRatio = (float)srcImgHeight/dstImgHeight;float widthRatio = (float)srcImgWidth/dstImgWidth;unsigned char *srcImgData = (unsigned char *)pSrcGrayImg->imageData;unsigned char *dstImgData = (unsigned char *)pDstGrayImg->imageData;int srcWidthStep = pSrcGrayImg->widthStep;int dstWidthStep = pDstGrayImg->widthStep;for (int i=0;i<dstImgHeight;i++){int tempHeight = int(i*heightRatio+0.5); //目标图像中i在原图像中对应的tempHeightif (tempHeight>=srcImgHeight){tempHeight = srcImgHeight-1;}for (int j=0;j<dstImgWidth;j++){int tempWidth = int(j*widthRatio+0.5);if (tempWidth>=srcImgWidth){tempWidth = srcImgWidth-1;}dstImgData[i*dstWidthStep+j]=srcImgData[tempHeight*srcWidthStep+tempWidth];}}cvNamedWindow("SrcImage",CV_WINDOW_AUTOSIZE);cvNamedWindow("DstImage",CV_WINDOW_AUTOSIZE);// 显示图像pSrccvShowImage("SrcImage",pSrcGrayImg);cvShowImage("DstImage",pDstGrayImg);cvWaitKey(0);cvDestroyAllWindows();cvReleaseImage(&pSrcGrayImg);cvReleaseImage(&pDstGrayImg);}