opencv 等比例缩放图像(图像尺寸不变)

效果图如下:

变换前:

opencv 等比例缩放图像(图像尺寸不变)_第1张图片

变换后:

opencv 等比例缩放图像(图像尺寸不变)_第2张图片

代码如下:

struct object_rect {
	int x;
	int y;
	int width;
	int height;
};

int resize_uniform(Mat &src, Mat &dst, Size dst_size, object_rect &effect_area)
{
	int w = src.cols;
	int h = src.rows;
	int dst_w = dst_size.width;
	int dst_h = dst_size.height;
	std::cout << "src: (" << h << ", " << w << ")" << std::endl;
	dst = Mat(Size(dst_w, dst_h), CV_8UC1, Scalar(1));

	float ratio_src = w*1.0 / h;
	float ratio_dst = dst_w*1.0 / dst_h;

	int tmp_w = 0;
	int tmp_h = 0;
	if (ratio_src > ratio_dst) {
		tmp_w = dst_w;
		tmp_h = floor((dst_w*1.0 / w) * h);
	}
	else if (ratio_src < ratio_dst) {
		tmp_h = dst_h;
		tmp_w = floor((dst_h*1.0 / h) * w);
	}
	else {
		resize(src, dst, dst_size);
		effect_area.x = 0;
		effect_area.y = 0;
		effect_area.width = dst_w;
		effect_area.height = dst_h;
		return 0;
	}

	std::cout << "tmp: (" << tmp_h << ", " << tmp_w << ")" << std::endl;
	Mat tmp;
	resize(src, tmp, Size(tmp_w, tmp_h));
	tmp.convertTo(tmp,CV_8UC1);
	
	if (tmp_w != dst_w) { //高对齐,宽没对齐
		int index_w = floor((dst_w - tmp_w) / 2.0);
		std::cout << "index_w: " << index_w << std::endl;
		for (int i = 0; i

 

你可能感兴趣的:(opencv,opencv,resize)