原理挺简单,不啰嗦,直接上代码了
void ImgResize(uchar* pSrcImg, uchar* pDstImg, int srcW, int srcH, int dstW, int dstH) { double rateH = (double)srcH /(double) dstH; double rateW = (double)srcW / (double)dstW; for (int i=0; i<dstH; i++) { int tSrcH = (int)(rateH*double(i) + 0.5); for (int j=0; j<dstW; j++) { int tSrcW = (int)(rateW * double(j) + 0.5); pDstImg[i*dstW+j] = pSrcImg[tSrcH*srcW+tSrcW]; } } } void ImgResizeTest() { cv::Mat srcImg = cv::imread("test.jpg", CV_LOAD_IMAGE_GRAYSCALE); if (srcImg.empty()) { printf("srcImg load error \n"); system("pause"); exit(-1); } int srcW = srcImg.cols; int srcH = srcImg.rows; int dstW1 = 2*srcW + 5; int dstH1 = 2*srcH + 5;//随便设定 int dstW2 = srcW/2 + 3; int dstH2 = srcH/2 + 3; uchar* pDstImg1 = new uchar[dstW1*dstH1]; uchar* pDstImg2 = new uchar[dstW2*dstH2]; ImgResize(srcImg.data, pDstImg1, srcW, srcH, dstW1, dstH1); ImgResize(srcImg.data, pDstImg2, srcW, srcH, dstW2, dstH2); cv::Mat dstImg1; dstImg1.create(dstH1,dstW1,CV_8UC1); memcpy(dstImg1.data, pDstImg1, dstW1*dstH1*sizeof(uchar)); cv::Mat dstImg2; dstImg2.create(dstH2,dstW2,CV_8UC1); memcpy(dstImg2.data, pDstImg2, dstW2*dstH2*sizeof(uchar)); cv::imshow("srcImg", srcImg); cv::imshow("dstImg1", dstImg1); cv::imshow("dstImg2", dstImg2); cv::waitKey(0); delete[] pDstImg1; }
最近邻算法的图像缩放代码
时间: 2024-11-05 21:52:23