这种方法的优点是速度快,在放大倍数不大的时候,与其他几种算法效果差别不大
1. 用 P (i,j)表示目标图像的像素点(RGB),P(x,y)表示源图像的像素点(RGB)
2. 求解水平和垂直缩放因子
double horFactor = srcWidth / dstWidth;double verFactor = srcHeight / dstHeight;
3.计算 P(i,j)在源图中的映射 P(x0,y0)
double x0 = i * verFactor;double y0 = j * horFactor;
4. 计算离P(x0,y0)最近的像素点 P(x,y)
int x = round(x0);int y = round(y0);
5. 得出目标图像 P(i,j)的像素值
P_dst(i,j).R = P_src(x,y).R;P_dst(i,j).G = P_src(x,y).G;P_dst(i,j).B = P_src(x,y).B;
6. Source Code
uint8_t *Scaling(uint8_t *src, int srcWidth, int srcHeight, int dstWidth, int dstHeight){ uint8_t *buf = new uint8_t[dstWidth * dstHeight * 3]; double horFactor = double(srcWidth) / dstWidth; //水平缩放因子 double verFactor = double(srcHeight) / dstHeight; //垂直缩放因子 int x0, y0; for (int i = 0; i < dstHeight; i++) { x0 = int(i * verFactor); for (int j = 0; j < dstWidth; j++) { y0 = int(j * horFactor); int srcOffset = (x0 * srcWidth + y0) * 3; // RGB int dstOffset = (i * dstWidth + j) * 3; //RGB buf[dstOffset + 0] = src[srcOffset + 0]; // B buf[dstOffset + 1] = src[srcOffset + 1]; // G buf[dstOffset + 2] = src[srcOffset + 2]; // R } } return buf;}
测试代码:
int main(int argc, char *argv[]){ JpegDecoder decoder("02.jpg"); auto &img = decoder.Decoder(); uint8_t *scale = Scaling(img.Data, img.Width, img.Height, img.Width / 2, img.Height / 2); cv::Mat src, dst; src.create(img.Height, img.Width, CV_8UC3); dst.create(img.Height / 2, img.Width / 2, CV_8UC3); src.data = img.Data; dst.data = scale; cv::imshow("src", src); cv::imshow("dst", dst); cv::waitKey(); return 0;}
JpegDecoder:
运行示例: