yolov5与fasterrcnn做map对比图的代码
时间: 2024-05-17 16:15:27 浏览: 20
以下是使用PyTorch实现的YOLOv5和Faster R-CNN的mAP对比图代码:
```python
import torch
import torchvision
import argparse
import utils
import os
# 设置参数
parser = argparse.ArgumentParser()
parser.add_argument('--data', type=str, default='coco', help='数据集名称')
parser.add_argument('--weights-yolo', type=str, default='yolov5s.pt', help='YOLOv5模型权重路径')
parser.add_argument('--weights-frcnn', type=str, default='fasterrcnn_resnet50_fpn_coco.pth', help='Faster R-CNN模型权重路径')
parser.add_argument('--iou-thres', type=float, default=0.5, help='IoU阈值')
parser.add_argument('--conf-thres', type=float, default=0.001, help='置信度阈值')
parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='输入图像尺寸')
args = parser.parse_args()
# 加载数据集
if args.data == 'coco':
test_set = torchvision.datasets.CocoDetection(root='./data/coco', annFile='./data/coco/annotations/instances_val2017.json')
num_classes = 80
elif args.data == 'voc':
test_set = torchvision.datasets.VOCDetection(root='./data/voc', image_set='val', transform=None, target_transform=None, download=True)
num_classes = 20
else:
raise ValueError('未知数据集名称')
# 创建YOLOv5模型
yolo_model = torch.hub.load('ultralytics/yolov5', 'custom', path=args.weights_yolo, source='local')
yolo_model.eval()
yolo_model.cuda()
# 创建Faster R-CNN模型
frcnn_model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=False, num_classes=num_classes)
frcnn_model.load_state_dict(torch.load(args.weights_frcnn))
frcnn_model.eval()
frcnn_model.cuda()
# 计算YOLOv5的AP
yolo_results = []
for idx in range(len(test_set)):
image, target = test_set[idx]
detections = yolo_model(image.unsqueeze(0).cuda(), img_size=args.img_size, conf_thres=args.conf_thres, iou_thres=args.iou_thres)
for detection in detections:
if detection is not None:
for x1, y1, x2, y2, conf, cls in detection:
yolo_results.append({'image_id': idx, 'category_id': cls.item(), 'bbox': [x1.item(), y1.item(), (x2-x1).item(), (y2-y1).item()], 'score': conf.item()})
yolo_eval = utils.evaluate(yolo_results, test_set.coco)
print('YOLOv5 mAP: {:.3f}'.format(yolo_eval.stats[0]))
# 计算Faster R-CNN的AP
frcnn_results = []
for idx in range(len(test_set)):
image, target = test_set[idx]
detections = frcnn_model([image.cuda()])
for detection in detections:
for box, conf, cls in zip(detection['boxes'], detection['scores'], detection['labels']):
frcnn_results.append({'image_id': idx, 'category_id': cls.item(), 'bbox': [box[0].item(), box[1].item(), (box[2]-box[0]).item(), (box[3]-box[1]).item()], 'score': conf.item()})
frcnn_eval = utils.evaluate(frcnn_results, test_set.coco)
print('Faster R-CNN mAP: {:.3f}'.format(frcnn_eval.stats[0]))
# 画出AP对比图
utils.plot_results([yolo_eval, frcnn_eval], names=['YOLOv5', 'Faster R-CNN'], save_dir=os.path.join('.', args.data+'_map.png'))
```
其中,`utils`是一个自定义的工具函数模块,包含了`evaluate`和`plot_results`函数。`evaluate`函数用于计算AP,`plot_results`函数用于画出AP对比图。这两个函数的实现可以参考[这个GitHub仓库](https://github.com/ultralytics/yolov5/blob/master/utils/general.py)。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)