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;
}
opencv环境下图像双线性插值重采样
于 2022-02-21 11:16:17 首次发布