• DETR实现目标检测(二)-利用自己训练的模型进行预测


    1、图片预测(CPU)

    关于DETR模型训练自己的数据集参考上篇文章:

    DETR实现目标检测(一)-训练自己的数据集-CSDN博客

    训练完成后的模型文件保存位置如下:

    准备好要预测的图片:

    然后直接调用模型进行预测,并设置置信度阈值来输出检测框:

    最后用plot函数来画出图片及预测框,效果如下:

    最后附上完整代码:

    1. from PIL import Image
    2. import matplotlib.pyplot as plt
    3. import torchvision.transforms as T
    4. from hubconf import *
    5. from util.misc import nested_tensor_from_tensor_list
    6. torch.set_grad_enabled(False)
    7. # COCO classes
    8. CLASSES = [
    9. '1'
    10. ]
    11. # colors for visualization
    12. COLORS = [[0.850, 0.325, 0.098]]
    13. # standard PyTorch mean-std input image normalization
    14. transform = T.Compose([
    15. T.Resize(800),
    16. T.ToTensor(),
    17. T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    18. ])
    19. # for output bounding box post-processing
    20. def box_cxcywh_to_xyxy(x):
    21. x_c, y_c, w, h = x.unbind(1)
    22. b = [(x_c - 0.5 * w), (y_c - 0.5 * h),
    23. (x_c + 0.5 * w), (y_c + 0.5 * h)]
    24. return torch.stack(b, dim=1)
    25. def rescale_bboxes(out_bbox, size):
    26. img_w, img_h = size
    27. b = box_cxcywh_to_xyxy(out_bbox)
    28. b = b * torch.tensor([img_w, img_h, img_w, img_h], dtype=torch.float32)
    29. return b
    30. def predict(im, model, transform):
    31. # mean-std normalize the input image (batch-size: 1)
    32. anImg = transform(im)
    33. data = nested_tensor_from_tensor_list([anImg])
    34. # propagate through the model
    35. outputs = model(data)
    36. # keep only predictions with 0.7+ confidence
    37. probas = outputs['pred_logits'].softmax(-1)[0, :, :-1]
    38. keep = probas.max(-1).values > 5*1e-8 # 置信度阈值
    39. # convert boxes from [0; 1] to image scales
    40. bboxes_scaled = rescale_bboxes(outputs['pred_boxes'][0, keep], im.size)
    41. return probas[keep], bboxes_scaled
    42. def plot_results(pil_img, prob, boxes):
    43. plt.figure(figsize=(16, 10))
    44. plt.imshow(pil_img)
    45. ax = plt.gca()
    46. colors = COLORS * 100
    47. prob2 = prob[:, 1:] # 第一列是背景,剔除
    48. for p, (xmin, ymin, xmax, ymax), c in zip(prob2, boxes.tolist(), colors):
    49. ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin,
    50. fill=False, color=c, linewidth=3))
    51. cl = p.argmax()
    52. text = f'{CLASSES[cl]}: {p[cl]:0.2f}'
    53. ax.text(xmin, ymin, text, fontsize=15,
    54. bbox=dict(facecolor='yellow', alpha=0.5))
    55. plt.axis('off')
    56. plt.show()
    57. if __name__ == "__main__":
    58. model = detr_resnet50(False, 1) # 这里与前面的num_classes数值相同,就是最大的category id值 + 1
    59. state_dict = torch.load(r"C:\Users\90539\Downloads\detr-main\detr-main\data\output\checkpoint.pth", map_location='cpu')
    60. model.load_state_dict(state_dict["model"])
    61. model.eval()
    62. # im = Image.open('data/coco_frame_count/train2017/001554.jpg')
    63. im = Image.open(r'C:\Users\90539\Downloads\detr-main\detr-main\data/coco_frame_count/val2017/09-12-52-0.png')
    64. scores, boxes = predict(im, model, transform)
    65. plot_results(im, scores, boxes)

  • 相关阅读:
    Pytorch squeeze() unsqueeze() 用法
    java毕业设计成品基于JavaWeb酒店管理系统开发与设计[包运行成功]
    【C++杂货铺】优先级队列的使用指南与模拟实现
    38.迪杰斯特拉(Dijkstra)算法
    C语言switch语句判断星期
    【Redis】SSM整合Redis&注解式缓存的使用
    【手撕STL】unordered_set、unordered_map(用哈希表封装)
    黑客入门教程(非常详细)从零基础入门到精通,看完这一篇就够了
    axios配置代理ip
    专业还没选,有必要报班自学python吗?
  • 原文地址:https://blog.csdn.net/Trisyp/article/details/139641887