使用opencv将Mat图像resize成检测输入的letterbox类型

本文介绍了两个Python代码片段,一个是使用OpenCV进行图像letterboxing(保持宽高比缩放)并添加边框,另一个是恢复在缩放后的letterboxed图像上的原始坐标。这两个函数在图像处理中常用于预处理,特别是针对不同大小的letterbox应用。
摘要由CSDN通过智能技术生成

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值