opencv环境下图像双线性插值重采样

bool RescaleImage(cv::Mat& image, unsigned int cols_new, unsigned int rows_new)
{
	if (cols_new * rows_new == 0 || image.data == nullptr) return 0;
	cv::Mat image_copy;
	image_copy.create(image.rows, image.cols, CV_8UC3);

	image_copy = image.clone();

	float y_float, x_float;
	unsigned int y_int, x_int;
	short ratio_x[2], ratio_y[2];
	float scale_x = (float)image_copy.cols / (float)cols_new;
	float scale_y = (float)image_copy.rows / (float)rows_new;

	image.release();
	image.create(rows_new, cols_new, CV_8UC3);
	for (int r = 0; r < rows_new; ++r)
	{
		y_float = (float)((r + 0.5) * scale_y - 0.5);
		y_int = floor(y_float);
		y_float -= y_int;

		if (y_int < 0)
		{
			y_float = 0;
			y_int = 0;
		}
		if (y_int >= image_copy.rows - 1)
		{
			y_float = 0;
			y_int = image_copy.rows - 2;
		}
		ratio_y[0] = (1.f - y_float) * 2048;
		ratio_y[1] = 2048 - ratio_y[0];
		for (int c = 0; c < cols_new; ++c)
		{
			x_float = (float)((c + 0.5) * scale_x - 0.5);
			x_int = floor(x_float);
			x_float -= x_int;
			if (x_int < 0)
			{
				x_float = 0;
				x_int = 0;
			}
			if (x_int >= image_copy.cols - 1)
			{
				x_float = 0;
				x_int = image_copy.cols - 2;
			}
			ratio_x[0] = (1.f - x_float) * 2048;
			ratio_x[1] = 2048 - ratio_x[0];
			for (int k = 0; k < image.channels(); ++k)
			{
				image.data[(r * cols_new + c) * image.channels() + k] =
					(image_copy.data[(y_int * image_copy.cols + x_int) * image.channels() + k] * ratio_x[0] * ratio_y[0] +
						image_copy.data[((y_int + 1) * image_copy.cols + x_int) * image.channels() + k] * ratio_x[0] * ratio_y[1] +
						image_copy.data[(y_int * image_copy.cols + x_int + 1) * image.channels() + k] * ratio_x[1] * ratio_y[0] +
						image_copy.data[((y_int + 1) * image_copy.cols + x_int + 1) * image.channels() + k] * ratio_x[1] * ratio_y[1]) >> 22;
			}
		}
	}
	return 1;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值