1.python代码
a.resize def my_letter_box(img, size=(640, 640)): # h, w, c = img.shape r = min(size[0] / h, size[1] / w) new_h, new_w = int(h * r), int(w * r) top = int((size[0] - new_h) / 2) left = int((size[1] - new_w) / 2) bottom = size[0] - new_h - top right = size[1] - new_w - left img_resize = cv2.resize(img, (new_w, new_h)) img = cv2.copyMakeBorder(img_resize, top, bottom, left, right, borderType=cv2.BORDER_CONSTANT, value=(114, 114, 114)) return img, r, left, top
b.返回原图坐标
def restore_box(boxes, r, left, top): # 返回原图上面的坐标 boxes[:, [0, 2]] -= left boxes[:, [1, 3]] -= top boxes[:, [0, 2]] /= r boxes[:, [1, 3]] /= r return boxes
2.c++代码
a.resize
float get_input_data_letterbox(cv::Mat mat, cv::Mat& img_new, int letterbox_rows, int letterbox_cols, int& left,int&top,bool bgr2rgb = false)
{
? ? /* letterbox process to support different letterbox size */
? ? if (!mat.data || letterbox_rows<1 || letterbox_cols<1)
? ? ? ? return 1.0;
? ? float scale_letterbox;
? ? int resize_rows;
? ? int resize_cols;
? ? if ((letterbox_rows * 1.0 / mat.rows) < (letterbox_cols * 1.0 / mat.cols))
? ? {
? ? ? ? scale_letterbox = (float)letterbox_rows * 1.0f / (float)mat.rows;
? ? }
? ? else
? ? {
? ? ? ? scale_letterbox = (float)letterbox_cols * 1.0f / (float)mat.cols;
? ? }
? ? resize_cols = int(scale_letterbox * (float)mat.cols);
? ? resize_rows = int(scale_letterbox * (float)mat.rows);
? ? //cv::Mat img_new(letterbox_rows, letterbox_cols, CV_8UC3);
? ? cv::resize(mat, mat, cv::Size(resize_cols, resize_rows));
? ? ?top = (letterbox_rows - resize_rows) / 2;
? ? int bot = (letterbox_rows - resize_rows + 1) / 2;
? ? ?left = (letterbox_cols - resize_cols) / 2;
? ? int right = (letterbox_cols - resize_cols + 1) / 2;
? ? // Letterbox filling
? ? cv::copyMakeBorder(mat, img_new, top, bot, left, right, cv::BORDER_CONSTANT, cv::Scalar(128, 128, 128));
? ? if (bgr2rgb)
? ? {
? ? ? ? cv::cvtColor(img_new, img_new, cv::COLOR_BGR2RGB);
? ? }
? ? return scale_letterbox;
}
b.返回原图坐标
?x0 = (x0 - left) /scale_letterbox;
?y0 = (y0 - top) /scale_letterbox;
?x1 = (x1 - left) /scale_letterbox;
?y1 = (y1 - top) /scale_letterbox;
? x0 = std::max(std::min(x0, (float)(src_cols - 1)), 0.f);
? y0 = std::max(std::min(y0, (float)(src_rows - 1)), 0.f);
? x1 = std::max(std::min(x1, (float)(src_cols - 1)), 0.f);
? y1 = std::max(std::min(y1, (float)(src_rows - 1)), 0.f);