在 MMDetection 3.0 系列中,可视化和绘制样本框(ground truth boxes)和检测框(detection boxes)。MMDetection 3.0 提供了一些新的 API 和工具,使得这一过程更加简洁和高效。下面是如何在 MMDetection 3.0 中实现这一目标的详细步骤。
安装 MMDetection 3.0
首先,确保你已经安装了 MMDetection 3.0 及其依赖项:
pip install mmdet==3.0.0
pip install -U openmim
mim install mmdet
加载模型和数据
以下是一个完整的示例代码,展示了如何在 MMDetection 3.0 中加载模型、进行推理,并绘制样本框和检测框。
import mmcv
import cv2
import matplotlib.pyplot as plt
from mmdet.apis import init_detector, inference_detector, show_result_pyplot
# 配置文件和模型检查点的路径
config_file = 'path/to/your/config/file.py'
checkpoint_file = 'path/to/your/checkpoint/file.pth'
# 初始化模型
model = init_detector(config_file, checkpoint_file, device='cuda:0')
# 测试图像路径
img = 'path/to/your/test/image.jpg'
# 推理检测
result = inference_detector(model, img)
# 可视化检测结果
show_result_pyplot(model, img, result, score_thr=0.3)
绘制样本框和检测框
在 MMDetection 3.0 中,你可以更方便地绘制样本框和检测框。以下是一个更详细的示例,包括如何绘制 ground truth boxes。
from mmdet.datasets import build_dataset
from mmdet.datasets.pipelines import Compose
# 加载配置文件
cfg = mmcv.Config.fromfile(config_file)
# 构建数据集
dataset = build_dataset(cfg.data.test)
# 获取样本数据
data = dataset[0]
# 提取图像和 ground truth boxes
img = mmcv.imread(data['img_metas'][0].data['filename'])
gt_bboxes = data['gt_bboxes'][0].data.numpy()
gt_labels = data['gt_labels'][0].data.numpy()
# 绘制 ground truth boxes (蓝色)
for bbox, label in zip(gt_bboxes, gt_labels):
img = cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (255, 0, 0), 2)
# 推理检测
result = inference_detector(model, img)
# 可视化检测结果 (红色)
show_result_pyplot(model, img, result, score_thr=0.3)