数字图像处理 || c++实现图像的缩放

  • 用了CImg库和opencv实现图片的缩放

题目:

Zooming and Shrinking Images by Pixel Replication

  • (a) Write a computer program capable of zooming and shrinking an image by pixel replication. Assume that the desired zoom/shrink factors are integers. You may ignore aliasing effects. You will need to download Fig. 2.19(a).
  • (b) Download Fig. 2.19 (a) and use your program to shrink the image from 1024 x 1024 to 256 x 256 pixels.
  • © Use your program to zoom the image in (b) back to 1024 x 1024. Explain the reasons for their differences.
// image2.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <algorithm>
#include "pch.h"
#include <iostream>
#include "CImg.h"
#include <Eigen3/Eigen/Dense>
#include <string>
#include <cstring>
#include <highgui/highgui.hpp>
using namespace cimg_library;
using namespace std;
using namespace Eigen;
CImg<int> near_change(CImg<int> img, int x, int y);
CImg<int> linear_change(CImg<int> img, int x, int y);
int main()
{
	
	// - - - - project 3 - - - -
	CImg<int> SrcImg("E:/Desktop/picture_process/Lenna/test.jpg");
	SrcImg.resize(256, 256,1,1,5);
	//SrcImg.resize(1024, 1024,1,1,5);
	SrcImg = near_change(SrcImg, 512, 512);
	//SrcImg = linear_change(SrcImg, 512, 512);
	SrcImg.display();

}
CImg<int> near_change(CImg<int> img, int x, int y) {
	double scale_x = (double) img.height()/x;
	double scale_y = (double) img.width()/y;
	CImg<int> pic(x,y,1,1);
	for (int i = 0; i < x; ++i) {
		for (int j = 0; j < y; j++) {
			int x0 = (int) i * scale_x;
			int y0 = (int) j * scale_y;
			pic(i, j) = img(x0, y0);
		}
	}
	return pic;
}
CImg<int> linear_change(CImg<int> img, int x, int y) {
	double scale_x = (double)img.height() / x;
	double scale_y = (double)img.width() / y;
	CImg<int> pic(x, y, 1, 1);
	for (int i = 0; i < x; i++) {
		for (int j = 0; j < y; j++) {
			float fx = (float)((i + 0.5)*scale_x - 0.5);
			float fy = (float)((j + 0.5)*scale_y - 0.5);
			int sx = cvFloor(fx);
			int sy = cvFloor(fy);
			fx -= sx;
			fy -= sy;
			sx = min(sx, img.height());
			sx = max(0, sx);
			sy = min(sy, img.width());
			sy = max(0, sy);
			short cbufx[2];
			short cbufy[2];
			cbufx[0] = cv::saturate_cast<short>((1.f - fx) * 2048);
			/*if ((1.f - fx) * 2048 < 0) {
				cbufx[0] = 0;
			}
			else if ((1.f - fx) * 2048 > 255) {
				cbufx[0] = 255;
			}
			else {
				cbufx[0] = (1.f - fx) * 2048;
			}*/
			cbufx[1] = 2048 - cbufx[0];
			/*if ((1.f - fy) * 2048 < 0) {
				cbufy[0] = 0;
			}
			else if ((1.f - fy) * 2048 > 255) {
				cbufy[0] = 255;
			}
			else {
				cbufy[0] = (1.f - fy) * 2048;
			}*/
			cbufy[0] = cv::saturate_cast<short>((1.f - fy) * 2048);
			cbufy[1] = 2048 - cbufy[0];
			pic(i, j) = (img(sx, sy)*cbufx[0]*cbufy[0] + img(sx+1,sy)*cbufx[1]*cbufy[0]+img(sx,sy+1)*cbufx[0]*cbufy[1]+img(sx+1,sy+1)*cbufx[1]*cbufy[1]) >>22;
		}
	}
	return pic;
}

猜你喜欢

转载自blog.csdn.net/perry0528/article/details/82860574