任意图像尺寸变成目标尺寸(包含相应的boxes的变换)

怎甘沉沦 提交于 2019-12-02 06:30:59
def image_preporcess(image, target_size, gt_boxes=None):    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)    ih, iw    = target_size    h,  w, _  = image.shape    scale = min(iw/w, ih/h)    nw, nh  = int(scale * w), int(scale * h)                                                                            # 寻找最小的,即使准备将最大边转换为目标尺寸如416,但最小边肯定不能变到目标尺寸(416)    image_resized = cv2.resize(image, (nw, nh))                                                                         # 将原始图像转换为需要的目标尺寸内,但不能完全填充完    image_paded = np.full(shape=[ih, iw, 3], fill_value=128.0)                                                          # 用128填充目标尺寸的矩阵    dw, dh = (iw - nw) // 2, (ih-nh) // 2                                                                               # 找出目标尺寸与原始图像转换后尺寸的差距的二分之一    image_paded[dh:nh+dh, dw:nw+dw, :] = image_resized                                                                  # 将改变后的原始图像尺寸的数据填充到中间位置,因为其它位置已经被128填充    image_paded = image_paded / 255.    if gt_boxes is None:        return image_paded    else:        gt_boxes[:, [0, 2]] = gt_boxes[:, [0, 2]] * scale + dw                                                          # 将原始坐标按照图像变化(原始图像变到目标图像)对应其bboxes的坐标        gt_boxes[:, [1, 3]] = gt_boxes[:, [1, 3]] * scale + dh                                                          # 将原始坐标按照图像变化(原始图像变到目标图像)对应其bboxes的坐标        return image_paded, gt_boxes                                                                                    #   gt_boxes将会对应变换后的图像位置,如[[263 211 324 339   8]                                                                                                                                                             #   [165 264 253 372   8]                                                                                                                                                              #  [241 194 295 299   8]]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!