原始图片尺寸:744*496
输入416*416 网络,图片尺寸失真调整:
输入416*416 网络,图片尺寸不失真调整:
c++ 代码:
#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
using namespace cv;
static const int INPUT_H = 416;
static const int INPUT_W = 416;
cv::Mat preprocess_img(cv::Mat& img) {
int w, h, x, y;
float r_w = INPUT_W / (img.cols*1.0);
float r_h = INPUT_H / (img.rows*1.0);
if (r_h > r_w) {
w = INPUT_W;
h = r_w * img.rows;
x = 0;
y = (INPUT_H - h) / 2;
}
else {
w = r_h * img.cols;
h = INPUT_H;
x = (INPUT_W - w) / 2;
y = 0;
}
cv::Mat re(h, w, CV_8UC3);
cv::resize(img, re, re.size(), 0, 0, cv::INTER_CUBIC);
cv::Mat out(INPUT_H, INPUT_W, CV_8UC3, cv::Scalar(128, 128, 128));
re.copyTo(out(cv::Rect(x, y, re.cols, re.rows)));
return out;
}
int main(int argc, char** argv) {
cv::Mat img = cv::imread("1.jpg");
cv::Mat direct_img;
cv::resize(img,direct_img,Size(416,416));
cv::Mat pr_img = preprocess_img(img);
imshow("不失真", pr_img);
imshow("失真", direct_img);
waitKey(0);
return 0;
}
总结:在目标检测中,图像预处理往往都需要做图像不失真尺寸调整。