网站建设评分标准,专门做外链的网站,商业网站后缀名,wordpress高级图片主题文章目录自适应缩放技术Letterbox介绍自适应缩放技术Letterbox流程自适应缩放Letterbox代码运行结果自适应缩放技术Letterbox介绍
由于数据集中存在多种不同和长宽比的样本图#xff0c;传统的图片缩放方法按照固定尺寸来进行缩放会造成图片扭曲变形的问题。自适应缩放技术通…
文章目录自适应缩放技术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), autoTrue, scaleFillFalse, scaleupTrue, stride32):# 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, interpolationcv2.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, valuecolor) # add borderreturn im, ratio, (dw, dh)
ori cv2.imread(rF:\python\object_detection\yolov7\test\2.jpg)
im, ratio, (dw, dh) letterbox(imori)
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后