defscale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None):# Rescale boxes (xyxy) from img1_shape to img0_shapeif ratio_pad isNone:# calculate from img0_shape
gain =min(img1_shape[0]/ img0_shape[0], img1_shape[1]/ img0_shape[1])# gain = old / new
pad =(img1_shape[1]- img0_shape[1]* gain)/2,(img1_shape[0]- img0_shape[0]* gain)/2# wh paddingelse:
gain = ratio_pad[0][0]
pad = ratio_pad[1]
boxes[...,[0,2]]-= pad[0]# x padding
boxes[...,[1,3]]-= pad[1]# y padding
boxes[...,:4]/= gain
clip_boxes(boxes, img0_shape)return boxes
xywh2xyxy
defxywh2xyxy(x):# Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
y = x.clone()ifisinstance(x, torch.Tensor)else np.copy(x)
y[...,0]= x[...,0]- x[...,2]/2# top left x
y[...,1]= x[...,1]- x[...,3]/2# top left y
y[...,2]= x[...,0]+ x[...,2]/2# bottom right x
y[...,3]= x[...,1]+ x[...,3]/2# bottom right yreturn y