目标检测笔记(四):自适应缩放技术Letterbox完整代码和结果展示

自适应缩放技术Letterbox介绍

由于数据集中存在多种不同和长宽比的样本图,传统的图片缩放方法按照固定尺寸来进行缩放会造成图片扭曲变形的问题。自适应缩放技术通过填充最少的灰边像素来将任意大小的图片调整为所需输入图片大小。

自适应缩放技术Letterbox流程

  1. 第一步:计算缩放比例。当原图的长宽不同时,将需要的尺寸大小除以原图的长宽,获得两种缩放比,选择较小的值作为缩放比例,因此图中选择的缩放比例为0.52。
  2. 第二步:分别计算缩放后的图像的长宽,原图的长宽分别乘以缩放比例,此时获得大小为 416×312。
  3. 第三步:计算填充的灰色像素。将需要的尺寸大小减去缩放后的短边大小,得到的值再采用 numpy 库中 np.mod 函数对 32 倍取余数的方式计算,然后通过平分得到对称两边需要填充的灰色像素。之所以用 32 取余,是因为 YOLOv5s 的网络需要对图像进行 5 次两倍下采样。

自适应缩放Letterbox代码

import numpy as np
import cv2

def letterbox(im, new_shape=(448, 448), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
    # Resize and pad image while meeting stride-multiple constraints
    shape = im.shape[:2]  # current shape [height, width]
    if isinstance(new_shape, int):
        new_shape = (new_shape, new_shape)

    # Scale ratio (new / old)
    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
    if not scaleup:  # only scale down, do not scale up (for better val mAP)
        r = min(r, 1.0)

    # Compute padding
    ratio = r, r  # width, height ratios
    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding
    if auto:  # minimum rectangle
        dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding
    elif scaleFill:  # stretch
        dw, dh = 0.0, 0.0
        new_unpad = (new_shape[1], new_shape[0])
        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios

    dw /= 2  # divide padding into 2 sides
    dh /= 2

    if shape[::-1] != new_unpad:  # resize
        im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
    im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border
    return im, ratio, (dw, dh)
ori = cv2.imread(r"F:\python\object_detection\yolov7\test\2.jpg")
im, ratio, (dw, dh) = letterbox(im=ori)
cv2.imshow('ori', ori)
cv2.imshow('new_img_bbox', im)
cv2.imwrite("2.jpg", ori)
cv2.imwrite("3.jpg", im)
cv2.waitKey(0)
cv2.destroyAllWindows()

运行结果

原图:
请添加图片描述
letterbox后
请添加图片描述

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZZY_dl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值