中国建设银行官网站纪念币河南网站托管维护
文章目录
- 自适应缩放技术Letterbox介绍
- 自适应缩放技术Letterbox流程
- 自适应缩放Letterbox代码
- 运行结果
自适应缩放技术Letterbox介绍
由于数据集中存在多种不同和长宽比的样本图,传统的图片缩放方法按照固定尺寸来进行缩放会造成图片扭曲变形的问题。自适应缩放技术通过填充最少的灰边像素来将任意大小的图片调整为所需输入图片大小。
自适应缩放技术Letterbox流程
- 第一步:计算缩放比例。当原图的长宽不同时,将需要的尺寸大小除以原图的长宽,获得两种缩放比,选择较小的值作为缩放比例,因此图中选择的缩放比例为0.52。
- 第二步:分别计算缩放后的图像的长宽,原图的长宽分别乘以缩放比例,此时获得大小为 416×312。
- 第三步:计算填充的灰色像素。将需要的尺寸大小减去缩放后的短边大小,得到的值再采用 numpy 库中 np.mod 函数对 32 倍取余数的方式计算,然后通过平分得到对称两边需要填充的灰色像素。之所以用 32 取余,是因为 YOLOv5s 的网络需要对图像进行 5 次两倍下采样。
自适应缩放Letterbox代码
import numpy as np
import cv2def 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 constraintsshape = 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 paddingratio = r, r # width, height ratiosnew_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 paddingif auto: # minimum rectangledw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh paddingelif scaleFill: # stretchdw, dh = 0.0, 0.0new_unpad = (new_shape[1], new_shape[0])ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratiosdw /= 2 # divide padding into 2 sidesdh /= 2if shape[::-1] != new_unpad: # resizeim = 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 borderreturn 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后