当前位置 博文首页 > cumtchw:opencv实现padding resize
#include <fstream>
#include <iostream>
#include <thread>
#include <string>
#include <vector>
#include <cuda_runtime_api.h>
#include "opencv2/opencv.hpp"
#include <unistd.h>
using namespace cv;
using namespace std;
void padding_resize(cv::InputArray src, cv::OutputArray dst, cv::Size size, double fx = 0, double fy = 0, int interpolation = cv::INTER_LINEAR)
{
float padd_w = 0;
float padd_h = 0;
//这里是找出原图中边长大的那个.然后先按照边长大的那个resize,然后边长小的就填充.
float r = std::min(float(size.width) / src.cols(), float(size.height) / src.rows());
int inside_w = round(src.cols() * r);//
int inside_h = round(src.rows() * r);//
padd_w = size.width - inside_w;//padd_w和padd_h其中一个是零.
padd_h = size.height - inside_h;
cout<<"padd_w:"<<padd_w<<",padd_h:"<<padd_h<<endl;
cv::resize(src, dst, cv::Size(inside_w, inside_h), fx, fy, interpolation);
padd_w = padd_w / 2;
padd_h = padd_h / 2;
cout<<"padd_w:"<<padd_w<<",padd_h:"<<padd_h<<endl;
//round函数是把一个小数四舍五入之后取整.round(2.2)=2.0000;round(2.5)=3.000;
//外层边框填充灰色
int top = int(round(padd_h - 0.1));
int bottom = int(round(padd_h + 0.1));
int left = int(round(padd_w - 0.1));
int right = int(round(padd_w + 0.1));
cout<<"top:"<<top<<",bottom:"<<bottom<<",left:"<<left<<",right:"<<right<<endl;
cv::copyMakeBorder(dst, dst, top, bottom, left, right, cv::BORDER_CONSTANT, cv::Scalar(114, 114, 114));//top, bottom, left, right分别表示在原图四周扩充边缘的大小
}
int main(int argc, char ** argv)
{
cv::Mat src = cv::imread("./rg2.jpeg");//720*405
cv::Mat dst;
padding_resize(src, dst, Size(1024, 1024), 0, 0,cv::INTER_LINEAR);
imwrite("./result.jpg", dst);
printf("this is in the main\n");
return 0;
}
打印信息如下:
padd_w:0,padd_h:448
padd_w:0,padd_h:224
top:224,bottom:224,left:0,right:0
this is in the main
cs