大家好,前面一篇文章介绍了torchvision的模型ResNet50实现图像分类,这里再给大家介绍一下如何使用torchvision自带的对象检测模型Faster-RCNN实现对象检测。Torchvision自带的对象检测模型是基于COCO数据集训练的,最小分辨率支持800, 最大支持1333的输入图像。

Faster-RCNN模型

Faster-RCNN模型的基础网络是ResNet50, ROI生成使用了RPN,加上头部组成。图示如下:

pytorch模型大小怎么输出 pytorch自带模型_图像分类

在torchvision框架下可以通过下面的代码直接下载预训练模型,

model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)model.eval()

对模型使用GPU加速支持

# 使用GPU

train_on_gpu = torch.cuda.is_available()if train_on_gpu:     model.cuda()

推理输出有三个信息分别为:

boxes:表示对象框scores:表示每个对象得分labels:表示对于的分类标签

图像检测

使用模型实现图像检测,支持90个类别的对象检测,代码实现如下:

def faster_rcnn_image_detection():
    image = cv.imread("D:/images/cars.jpg")
    blob = transform(image)
    c, h, w = blob.shape
    input_x = blob.view(1, c, h, w)
    output = model(input_x.cuda())[0]
    boxes = output['boxes'].cpu().detach().numpy()
    scores = output['scores'].cpu().detach().numpy()
    labels = output['labels'].cpu().detach().numpy()
    index = 0
    for x1, y1, x2, y2 in boxes:
        if scores[index] > 0.5:
            print(x1, y1, x2, y2)
            cv.rectangle(image, (np.int32(x1), np.int32(y1)),
                         (np.int32(x2), np.int32(y2)), (0, 255, 255), 1, 8, 0)
            label_id = labels[index]
            label_txt = coco_names[str(label_id)]
            cv.putText(image, label_txt, (np.int32(x1), np.int32(y1)), cv.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 255), 1)
        index += 1
    cv.imshow("Faster-RCNN Detection Demo", image)
    cv.waitKey(0)
    cv.destroyAllWindows()

运行结果下:

pytorch模型大小怎么输出 pytorch自带模型_图像分类_02

视频实时对象检测

基于OpenCV实现视频文件或者摄像头读取,完成视频的实时对象检测,代码实现如下:

1capture = cv.VideoCapture(

 运行结果如下:

pytorch模型大小怎么输出 pytorch自带模型_pytorch自带网络_03